网页禁止复制

一、通过 JavaScript 实现
我们可以通过 JS 代码来禁用网页的复制事件、剪切事件、选择内容事件甚至是右键菜单事件。

// 禁止右键菜单
document.oncontextmenu = function(){ return false; };
// 禁止文字选择
document.onselectstart = function(){ return false; };
// 禁止复制
document.oncopy = function(){ return false; };
// 禁止剪切
document.oncut = function(){ return false; };
二、通过 HTML 实现
除了上面提到的方法,我们也可以通过设置标签属性的方式直接禁用页面复制剪切操作:

<body 
    oncopy="return false" 
    oncut="return false;" 
    onselectstart="return false" 
    oncontextmenu="return false"
>
</body>

该方法本质上与 JS 实现方式相同。

通过以下 JS 代码可以恢复页面复制、剪切及内容选中功能:

document.body.oncopy = null;
document.body.oncut = null;
document.body.onselectstart = null;
document.body.oncontextmenu = null;

三、通过 CSS 实现
我们也可以通过 CSS 样式,禁止页面内容被选中,从而达到限制复制操作的目的:

body {
  -moz-user-select:none; /* Firefox私有属性 */
  -webkit-user-select:none; /* WebKit内核私有属性 */
  -ms-user-select:none; /* IE私有属性(IE10及以后) */
  -khtml-user-select:none; /* KHTML内核私有属性 */
  -o-user-select:none; /* Opera私有属性 */
  user-select:none; /* CSS3属性 */
}

恢复页面内容选中功能,需要通过 JS 代码进行实现:

document.body.style.webkitUserSelect = 'auto'; // Firefox
document.body.style.userSelect = 'auto'; // Chrome

原文

posted @ 2023-12-25 16:44  lambertlt  阅读(58)  评论(0编辑  收藏  举报