使用JavaScript启用阻止文本选择

Pat*_*ick 20 javascript css

我最近遇到了一个禁用文本选择网站,阻止任何人轻易复制和粘贴文本.我有一个书签,禁止使用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"
}
Run Code Online (Sandbox Code Playgroud)

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

我的上下文菜单bookmarklet中的解决方案也可能是必需的:

javascript:void(document.onmousedown=null);
void(document.onclick=null);
void(document.oncontextmenu=null)
Run Code Online (Sandbox Code Playgroud)

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

-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
user-select: none;
Run Code Online (Sandbox Code Playgroud)

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

ccp*_*zza 23

在一个讨厌的网络应用程序上遇到同样的问题,我必须每天在工作中使用它.

尝试编写我自己的书签,它会覆盖onselectstart事件处理程序,但它不起作用,显然是因为必须修改的附加CSS规则.

然后我找到了Alan Hogan的" 启用所有文本选择"书签,为我解决了这个问题.书签的唯一问题是它不处理帧/ iframe.

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

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

javascript:(function(){function ats(){var styles='*,p,div{user-select:text !important;-moz-user-select:text !important;-webkit-user-select:text !important;}';jQuery('head').append(jQuery('<style />').html(styles));var allowNormal=function(){return true;};jQuery('*[onselectstart], *[ondragstart], *[oncontextmenu], #songLyricsDiv').unbind('contextmenu').unbind('selectstart').unbind('dragstart').unbind('mousedown').unbind('mouseup').unbind('click').attr('onselectstart',allowNormal).attr('oncontextmenu',allowNormal).attr('ondragstart',allowNormal);}function atswp(){if(window.jQuery){ats();}else{window.setTimeout(atswp,100);}}if(window.jQuery){ats();}else{var s=document.createElement('script');s.setAttribute('src','http://code.jquery.com/jquery-1.9.1.min.js');document.getElementsByTagName('body')[0].appendChild(s);atswp();}})();
Run Code Online (Sandbox Code Playgroud)

它有局限性,因为它不能在嵌套框架内工作.


..btw,为了使bookmarklet代码可读,我在http://subsimple.com/bookmarklets/jsbuilder.htm上使用了Bookmarkelt Builder - 只需粘贴缩小的bookmarklet文本并单击Format按钮; 这个工具为我节省了很多时间.


小智 6

与网站有同样的问题.

CSS无法解决此问题,因为只要您尝试选择文本,Javascript就会发挥作用.

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

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