使用 JavaScript 启用被阻止的文本选择

新手上路,请多包涵

我最近遇到一个 禁用文本选择的网站,阻止任何人轻松复制和粘贴文本。我有一个小书签,它禁止使用 JavaScript 阻止上下文菜单的类似尝试,我想知道是否可以对文本选择做类似的事情。

 function disableSelection(target){
if (typeof target.onselectstart!="undefined") //For IE
    target.onselectstart=function(){return false}
else if (typeof target.style.MozUserSelect!="undefined") //For Firefox
    target.style.MozUserSelect="none"
else //All other route (For Opera)
    target.onmousedown=function(){return false}
target.style.cursor = "default"
}

在其他地方调用函数 disableSelection(document.body)

我的上下文菜单书签中的解决方案也可能是必要的:

 javascript:void(document.onmousedown=null);
void(document.onclick=null);
void(document.oncontextmenu=null)

最后,我 在 StackOverflow 的其他地方 看到也可以使用 CSS:

 -webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
user-select: none;

有没有一种方法可以同时解决所有这些问题,并通过我的浏览器结束这种暴政?我如何为所有元素启用 MozUserSelect / SelectStart 并设置 CSS 属性?

原文由 Patrick 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 649
2 个回答

查看 _Alan Hogan 的启用所有文本选择书签_。小书签的唯一问题是它不处理框架/iframe(这是浏览器安全问题,因此不太可能对其进行处理)。

作为一个额外的好处,它还可以在阻止它的页面上启用鼠标右键单击事件。

创建一个书签(例如,将任何页面的 URL 左侧的图标拖到书签栏),右键单击并选择 Edit ,重命名为有意义的名称,然后在 URL 字段中插入以下代码:

 javascript:(function(){function%20allowTextSelection(){window.console&&console.log('allowTextSelection');var%20style=document.createElement('style');style.type='text/css';style.innerHTML='*,p,div{user-select:text%20!important;-moz-user-select:text%20!important;-webkit-user-select:text%20!important;}';document.head.appendChild(style);var%20elArray=document.body.getElementsByTagName('*');for(var%20i=0;i<elArray.length;i++){var%20el=elArray[i];el.onselectstart=el.ondragstart=el.ondrag=el.oncontextmenu=el.onmousedown=el.onmouseup=function(){return%20true};if(el%20instanceof%20HTMLInputElement&&['text','password','email','number','tel','url'].indexOf(el.type.toLowerCase())>-1){el.removeAttribute('disabled');el.onkeydown=el.onkeyup=function(){return%20true};}}}allowTextSelection();})();


要使小书签代码可读,您可以使用位于 http://subsimple.com/bookmarklets/jsbuilder.htm 的 Bookmarkelt Builder - 只需粘贴缩小的小书签文本并单击格式按钮。

原文由 ccpizza 发布,翻译遵循 CC BY-SA 4.0 许可协议

与网站有同样的问题。

CSS 无法解决此问题,因为每当您尝试选择文本时,Javascript 就会发挥作用。

有两种方法可以解决这个问题 1) 在您的网络浏览器上禁用 Javascript。看看这个以供参考。 http://browsers.about.com/od/googlechrome/ss/disable-javascript-chrome-windows.htm 2) 打开 javascript 控制台。我正在使用 chrome(在 Mac 上单击 shift+command+C,在 Ubuntu 和 Windows 上单击 f12)

复制此代码 document.body.onselectstart = function() {return true;}; 并将其粘贴到控制台中,然后按回车键。

原文由 Kanhailal Murmu 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题