有时我们会遇到禁止用户复制网站的文字内容,例如小说网站,我们可以通过下列方法提高复制内容的门槛,来实现我们的目标。
1. 禁用选中和右键:
在 <body> 标签中添加以下代码:
<body leftmargin=0 topmargin=0 oncontextmenu='return false' ondragstart='return false' onselectstart ='return false' onselect='document.selection.empty()' oncopy='document.selection.empty()' onbeforecopy='return false' onmouseup='document.selection.empty()'>
οncοntextmenu='return false' 禁止右键
οndragstart='return false' 禁止拖动
onselectstart ='return false' 禁止选中
οnselect='document.selection.empty()' 禁止选中
οncοpy='document.selection.empty()' 禁止复制
onbeforecopy='return false' 禁止复制
οnmοuseup='document.selection.empty()'
2. 禁止网页另存为:在 <body> 后面加入以下代码:
<noscript>
<iframe src="*.htm"></iframe>
</noscript>
这时在电脑端已经无法选择复制,但是在移动端还可以选中复制,再添加以下 css 代码用来禁止选中文字。
3. 禁止选中文字
*{
moz-user-select: -moz-none;
-moz-user-select: none;
-o-user-select:none;
-khtml-user-select:none;
-webkit-user-select:none;
-ms-user-select:none;
user-select:none;
}
这时正常的选择复制都已经被禁用但是还可以用浏览器的查看源码和调试工具来直接从代码中复制内容。
4. 禁用 F12 按键
// 禁用 F12
window.onkeydown = window.onkeyup = window.onkeypress = function (event) {
// 判断是否按下 F12,F12 键码为 123
if (event.keyCode == 123) {event.preventDefault(); // 阻止默认事件行为
window.event.returnValue = false;
}
}
将上面的代码复制到新建 js 文件,然后加在 <body></body> 之间:
<script src="<?php $this->options->themeUrl('f12.js');?>"></script>
5. 禁用调试工具
var threshold = 160; // 打开控制台的宽或高阈值
// 每秒检查一次
var check = setInterval(function() {
if (window.outerWidth - window.innerWidth > threshold ||
window.outerHeight - window.innerHeight > threshold) {
// 如果打开控制台,则刷新页面
window.location.reload();}
}, 1000);
6. 禁止鼠标右键
document.oncontextmenu = function(event) {if (window.event) {event = window.event;}
try {
var the = event.srcElement;
if (!((the.tagName == "INPUT" && the.type.toLowerCase() == "text") || the.tagName == "TEXTAREA")) {return false;}
return true;
} catch (e) {return false;}
}
至此,已经限制了大部分的复制功能,但是还不能彻底禁止,更完善的方法还需学习整理。
© 版权声明
本站技术资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权请联系邮箱i@lho.cc删除!
THE END