我在实现JavaScript代码以禁用复制/粘贴,打印屏幕和使用JavaScript和jQuery右键单击(上下文菜单(时遇到困难。
问题是,如果我注释掉涉及禁用复制粘贴和右键单击功能的 jQuery 的代码块,则不会禁用打印屏幕功能(我已经通过在 MS Paint 中粘贴进行了测试(。
这是我的代码:
<!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>
使用此CSS而不是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>