首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法使用JavaScript禁用打印屏幕、复制/粘贴和右键单击功能

问无法使用JavaScript禁用打印屏幕、复制/粘贴和右键单击功能
EN

Stack Overflow用户
提问于 2019-08-07 02:35:10
回答 1查看 286关注 0票数 0

我在使用JavaScript和jQuery实现一个禁用复制/粘贴、打印屏幕和右键单击(上下文菜单)的JavaScript代码时遇到了困难。

问题是,如果我注释掉涉及禁用复制粘贴和右键单击功能的jQuery代码块,打印屏幕功能不会被禁用(我已经在MS Paint中通过粘贴进行了测试)。

下面是我的代码:

代码语言:javascript
复制
<!DOCTYPE html>

<head>
<title>Disable Print Screen Demo</title>
<style>
    .container {
        background-color: lightblue;
        width: 400px;
        height: 200px;
        margin: 0px 0px 0px 390px;
        padding: 50px;
        border: 2px solid blue;
    }
</style>

<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
</head>

<body>
<div class="container">
    <h1>Disable Print Screen Demo</h1>
    <hr />
    <p>
        Try to press the <b>"PrintScreen/SysRq"</b> key on your keyboard. 
    The user will get an alert that PrintScreen is Disabled and the content 
    will not be copied to the clipboard. 
    </p>
    </div>

<script>

// Disable Mouse Right Click
$(document).ready(function() {
    $("body").on("contextmenu", function(e){
        return false;
    });
});

// Disable PrintScreen (Screenshot)
document.addEventListener("keyup", function (e) {
    var keyCode = e.keyCode ? e.keyCode : e.which;
    if (keyCode == 44) {
        stopPrntScr();
        alert("Print Screen is Disabled!");
    }
});

function stopPrntScr() {
    var inpFld = document.createElement("input");
    inpFld.setAttribute("value", ".");
    inpFld.setAttribute("width", "0");
    inpFld.style.height = "0px";
    inpFld.style.width = "0px";
    inpFld.style.border = "0px";
    document.body.appendChild(inpFld);
    inpFld.select();
    document.execCommand("copy");
    inpFld.remove(inpFld);


    // Disable Cut Copy Paste
    $(document).ready(function(){
    $('body').bind('cut copy paste', function(e){
        e.preventDefault();
    });
});
}
</script>

</body>

</html>
EN

回答 1

Stack Overflow用户

发布于 2021-07-24 23:03:37

使用此CSS而不是javascript,这将阻止在浏览器中选择文本。

代码语言:javascript
复制
<body class="noselect">
      your content goes here...
</body>

    <style>
        .noselect {
            -webkit-touch-callout: none; /* iOS Safari */
            -webkit-user-select: none; /* Safari */
            -moz-user-select: none; /* Old versions of Firefox */
            -ms-user-select: none; /* Internet Explorer/Edge */
            user-select: none; /* Non-prefixed version, currently
                                      supported by Chrome, Edge, Opera and Firefox */
        }
    </style>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57382098

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档