前言
最近接了个需求,禁止网页中的内容被复制粘贴,解决方案网上都有,主要方法是 添加CSS以及修改元素的原生事件
css代码
#eleselector{
/*禁止文本被选中*/
-moz-pointer-events:none;
-webkit-touch-callout:none;
-webkit-user-select:none;
-khtml-user-select:none;
-moz-user-select:none;
-ms-user-select:none;
user-select:none;
/*禁止移动端图片长按触发操作系统菜单保存文件*/
pointer-events:none;
-webkit-pointer-events:none;
-ms-pointer-events:none;
-moz-pointer-events:none;
}
#eleselector button{
/*禁止长按的元素子元素会出现不能点击的情况,需要对子元素做出以下调整*/
pointer-events:auto;
-webkit-pointer-events:auto;
-ms-pointer-events:auto;
-moz-pointer-events:auto;
}
html代码
<!--代码比较好懂,禁止该元素的右键菜单以及拖动事件-->
<div ondragstart="return false" oncontextmenu="return false" onselectstart ="return false" onselect="document.selection.empty()" oncopy="document.selection.empty()" onbeforecopy="return false" onmouseup="document.selection.empty()">
</div>
写到这里,没有什么难度,以上代码 可以在 微信内置浏览器以及 桌面版Chorem、桌面版QQ浏览器 等大部分主流浏览器中实现禁止选中以及复制的功能。
但是,在UC浏览器中翻车了...
UC浏览器中长按网页会出现浏览器自带的菜单,并且更坑的是点击自带菜单的【复制】不会触发选中元素的copy事件(大胆假设从触发长按事件到复制整个流程走的安卓的操作系统,已经不是网页可以控制的了) - -
最后找到了解决方案 ,只需加上一行meta标签,即可禁止UC浏览器弹出菜单,选中并复制内容,直接上代码
正文
<meta name="browsermode" content="application"/><!-- uc不能复制网页内容 需要复制去掉即可-->
原文链接: https://www.jianshu.com/p/96aa4e28dd4b
续
华为浏览器(花瓣浏览器) 仍然可以弹出菜单,并且可以复制选中的文本,好在可以监听到元素的copy事件,可以用JS处理复制的内容
/*清空要复制的内容*/
document.body.onbeforecopy = function () {
window.getSelection().removeAllRanges();
}
document.body.oncopy = function () {
window.getSelection().removeAllRanges();
return false;
}