A Universal Script to Re-Enable the Selection and Copying

Enables select, right-click, copy and drag on pages that disable them. Enhanced Feature: Alt Key HyperLink Text Selection

目前为 2021-06-20 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name A Universal Script to Re-Enable the Selection and Copying
  3. // @name:zh-TW A Universal Script to Re-Enable the Selection and Copying
  4. // @version 1.7.7.3
  5. // @description Enables select, right-click, copy and drag on pages that disable them. Enhanced Feature: Alt Key HyperLink Text Selection
  6. // @description:zh-TW 解除禁止復制、剪切、選擇文本、右鍵菜單的限制。破解鎖右鍵、文字複製、文字選取。增強功能:Alt鍵超連結文字選取。
  7. // @include /^https?\:\/\//
  8. // @grant none
  9. // @run-at document-start
  10. // @namespace https://greasyfork.org/users/371179
  11. // ==/UserScript==
  12. (function $$($) {
  13. 'use strict';
  14. if (document == null || !document.documentElement) return window.requestAnimationFrame($$); // this is tampermonkey bug?? not sure
  15. //console.log('script at', location)
  16.  
  17. function isSupportAdvancedEventListener() {
  18. if ('_b1750' in $) return $._b1750
  19. var prop = 0;
  20. document.createAttribute('z').addEventListener('', null, {
  21. get passive() {
  22. prop++;
  23. },
  24. get once() {
  25. prop++;
  26. }
  27. });
  28. return ($._b1750 = prop == 2);
  29. }
  30.  
  31. var getSelection = window.getSelection || Error()(),
  32. requestAnimationFrame = window.requestAnimationFrame || Error()(),
  33. getComputedStyle = window.getComputedStyle || Error()();
  34.  
  35. $ = {
  36. utSelectionColorHack: 'msmtwejkzrqa',
  37. utTapHighlight: 'xfcklblvkjsj',
  38. utLpSelection: 'gykqyzwufxpz',
  39. ksFuncReplacerNonFalse: '___dqzadwpujtct___',
  40. ksEventReturnValue: ' ___ndjfujndrlsx___',
  41. ksSetData: '___rgqclrdllmhr___',
  42.  
  43. mAlert_DOWN: function() {}, //dummy function in case alert replacement is not valid
  44. mAlert_UP: function() {}, //dummy function in case alert replacement is not valid
  45.  
  46. isAnySelection: function() {
  47. var sel = getSelection();
  48. return !sel ? null : (typeof sel.isCollapsed == 'boolean') ? !sel.isCollapsed : (sel.toString().length > 0);
  49. },
  50.  
  51. createCSSElement: function(cssStyle, container) {
  52. var css = document.createElement('style'); //slope: DOM throughout
  53. css.type = 'text/css';
  54. css.innerHTML = cssStyle;
  55. if (container) container.appendChild(css);
  56. return css;
  57. },
  58.  
  59. createFakeAlert: function(_alert) {
  60. if (typeof _alert != 'function') return null;
  61.  
  62. function alert(msg) {
  63. alert.__isDisabled__() ? console.log("alert msg disabled: ", msg) : _alert.apply(this, arguments);
  64. };
  65. alert.toString = () => "function alert() { [native code] }";
  66. return alert;
  67. },
  68.  
  69. createFuncReplacer: function(originalFunc, pName, resFX) {
  70. resFX = function(ev) {
  71. var res = originalFunc.apply(this, arguments);
  72. if (!this || this[pName] != resFX) return res; // if this is null or undefined, or this.onXXX is not this function
  73. if (res === false) return; // return undefined when "return false;"
  74. originalFunc[$.ksFuncReplacerNonFalse] = true;
  75. this[pName] = originalFunc; // restore original
  76. return res;
  77. }
  78. resFX.toString = () => originalFunc.toString();
  79. return resFX;
  80. },
  81.  
  82. listenerDisableAll: function(evt) {
  83. var elmNode = evt.target;
  84. while (elmNode && elmNode.nodeType > 0) { //i.e. HTMLDocument or HTMLElement
  85. var pName = 'on' + evt.type
  86. var f = elmNode[pName];
  87. if (typeof f == 'function' && f[$.ksFuncReplacerNonFalse] !== true) {
  88. var nf = $.createFuncReplacer(f, pName);
  89. nf[$.ksFuncReplacerNonFalse] = true;
  90. elmNode[pName] = nf;
  91. }
  92. elmNode = elmNode.parentNode;
  93. }
  94. },
  95.  
  96. onceCssHighlightSelection: () => {
  97. if (document.documentElement.hasAttribute($.utLpSelection)) return;
  98. $.onceCssHighlightSelection = null
  99. var s = [...document.querySelectorAll('a,p,div,span,b,i,strong,li')].filter(elm => elm.childElementCount === 0); // randomly pick an element containing text only to avoid css style bug
  100. var elm = !s.length ? document.body : s[s.length >> 1];
  101. var selectionStyle = getComputedStyle(elm, ':selection');
  102. if (/^rgba\(\d+,\s*\d+,\s*\d+,\s*0\)$/.test(selectionStyle.getPropertyValue('background-color'))) document.documentElement.setAttribute($.utSelectionColorHack, "");
  103. var elmStyle = getComputedStyle(elm)
  104. if (/^rgba\(\d+,\s*\d+,\s*\d+,\s*0\)$/.test(elmStyle.getPropertyValue('-webkit-tap-highlight-color'))) document.documentElement.setAttribute($.utTapHighlight, "");
  105. },
  106.  
  107. isCurrentClipboardDataReplaced: function(clipboardData) {
  108. var items = clipboardData ? clipboardData.items : null;
  109. if (items && items.length > 0) {
  110. for (var i = 0, l = items.length; i < l; i++) {
  111. if (items[i].type == 'text/plain') return true;
  112. }
  113. }
  114. return false;
  115. },
  116.  
  117. replacementSetData: function(_setData, evt) {
  118. if (typeof _setData != 'function') return;
  119.  
  120. function setData() {
  121. var res = _setData.apply(this, arguments);
  122. try {
  123. if (evt.clipboardData === this && this.setData === setData && evt.cancelable && evt.defaultPrevented === false) {
  124. if ($.isCurrentClipboardDataReplaced(evt.clipboardData)) {
  125. evt.preventDefault();
  126. if (evt.defaultPrevented === true) {
  127. this.setData = _setData;
  128. delete this[$.ksSetData];
  129. }
  130. }
  131. }
  132. } catch (e) {}
  133. return res;
  134. }
  135. setData.toString = () => _setData.toString();
  136. evt.clipboardData.setData = setData;
  137. evt.clipboardData[$.ksSetData] = _setData;
  138. },
  139.  
  140.  
  141. enableSelectClickCopy: function() {
  142.  
  143. $.eyEvts = ['keydown', 'keyup', 'copy', 'contextmenu', 'select', 'selectstart', 'dragstart', 'beforecopy']; //slope: throughout
  144.  
  145. function isDeactivePreventDefault(evt) {
  146. if ($.bypass) return false;
  147. var j = $.eyEvts.indexOf(evt.type);
  148. switch (j) {
  149. case 3:
  150. if(evt.target instanceof Element && (evt.target.textContent||"").trim().length===0)return false; //exclude elements like video
  151. return true;
  152. case -1:
  153. return false;
  154. case 0:
  155. case 1:
  156. return (evt.keyCode == 67 && (evt.ctrlKey || evt.metaKey) && !evt.altKey && !evt.shiftKey && $.isAnySelection() === true);
  157. case 2:
  158.  
  159. if (!('clipboardData' in evt && 'setData' in DataTransfer.prototype)) return true; // Event oncopy not supporting clipboardData
  160. // see the richtext hack in https://www.cleancss.com/css-beautify/
  161. // see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/copy_event
  162. // see https://w3c.github.io/clipboard-apis/#widl-ClipboardEvent-clipboardData
  163.  
  164. if ($.isCurrentClipboardDataReplaced(evt.clipboardData) == false) { //no replacement data
  165. if (!evt.clipboardData[$.ksSetData] && evt.cancelable && evt.defaultPrevented === false) $.replacementSetData(evt.clipboardData.setData, evt);
  166. return true;
  167. }
  168. var trimedSelectionText = getSelection().toString().trim()
  169. if (trimedSelectionText) {
  170. //there is replacement data and the selection is not empty
  171. console.log("copy event - clipboardData replacement is allowed and the selection is not empty", trimedSelectionText)
  172. return false;
  173. } else {
  174. //there is replacement data and the selection is empty
  175. return false;
  176. }
  177. break; // for js formatting only
  178.  
  179. default:
  180. return true;
  181. }
  182. }
  183.  
  184. Event.prototype.preventDefault = (function(f) {
  185. function preventDefault() {
  186. if (!isDeactivePreventDefault(this)) f.apply(this);
  187. }
  188. preventDefault.toString = () => f.toString();
  189. return preventDefault;
  190. })(Event.prototype.preventDefault);
  191.  
  192. Object.defineProperty(Event.prototype, "returnValue", {
  193. get() {
  194. return $.ksEventReturnValue in this ? this[$.ksEventReturnValue] : true;
  195. },
  196. set(newValue) {
  197. if (!isDeactivePreventDefault(this) && newValue === false) this.preventDefault();
  198. this[$.ksEventReturnValue] = newValue;
  199. },
  200. enumerable: true,
  201. configurable: true
  202. });
  203.  
  204. for (var i = 2, eventsCount = $.eyEvts.length; i < eventsCount; i++) {
  205. document.addEventListener($.eyEvts[i], $.listenerDisableAll, true); // Capture Event; passive:false; expected occurrence COMPLETELY before Target Capture and Target Bubble
  206. }
  207.  
  208. var _alert = window.alert; //slope: temporary
  209. if (typeof _alert == 'function') {
  210. var _mAlert = $.createFakeAlert(_alert);
  211. if (_mAlert) {
  212. var clickBlockingTo = 0;
  213. _mAlert.__isDisabled__ = () => clickBlockingTo > +new Date;
  214. $.mAlert_DOWN = () => (clickBlockingTo = +new Date + 50);
  215. $.mAlert_UP = () => (clickBlockingTo = +new Date + 20);
  216. window.alert = _mAlert
  217. }
  218. }
  219.  
  220. },
  221.  
  222. lpCheckPointer: function(targetElm) {
  223. if (targetElm && targetElm.nodeType == 1 && targetElm.matches('*:hover')) {
  224. if (getComputedStyle(targetElm).getPropertyValue('cursor') == 'pointer' && targetElm.textContent) return true;
  225. }
  226. return false;
  227. },
  228.  
  229. lpFullCancel: function(evt, toPreventDefault) {
  230. $.bypass = true;
  231. !toPreventDefault || evt.preventDefault()
  232. evt.stopPropagation();
  233. evt.stopImmediatePropagation();
  234. $.bypass = false;
  235. },
  236.  
  237. lpMouseDown: function(evt) {
  238. $.lpMouseActive = 0;
  239. if (evt.altKey && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && evt.button === 0 && $.lpCheckPointer(evt.target)) {
  240. $.lpMouseActive = 1;
  241. $.lpFullCancel(evt, false);
  242. document.documentElement.setAttribute($.utLpSelection, '');
  243. }
  244. },
  245.  
  246. lpMouseUp: function(evt) {
  247. if ($.lpMouseActive == 1) {
  248. $.lpMouseActive = 2;
  249. document.documentElement.removeAttribute($.utLpSelection);
  250. $.lpFullCancel(evt, false);
  251. if ($.onceCssHighlightSelection) window.requestAnimationFrame($.onceCssHighlightSelection);
  252. }
  253. },
  254.  
  255. lpClick: function(evt) {
  256. if ($.lpMouseActive == 2) {
  257. $.lpFullCancel(evt, false);
  258. }
  259. },
  260.  
  261. lpEnable: function() { // this is an optional feature for modern browser
  262. // the built-in browser feature has already disabled the default event behavior, the coding is just to ensure no "tailor-made behavior" occuring.
  263. document.addEventListener('mousedown', $.lpMouseDown, {
  264. capture: true,
  265. passive: true
  266. })
  267. document.addEventListener('mouseup', $.lpMouseUp, {
  268. capture: true,
  269. passive: true
  270. })
  271. document.addEventListener('click', $.lpClick, {
  272. capture: true,
  273. passive: true
  274. })
  275. },
  276.  
  277. mainEnableScript: () => {
  278. var cssStyleOnReady = `
  279.  
  280. *, body *, div, span, body *::before, body *::after, *:hover, *:link, *:visited, *:active , *[style], *[class]{
  281. -khtml-user-select: auto !important; -moz-user-select: auto !important; -ms-user-select: auto !important;
  282. -webkit-touch-callout: default !important; -webkit-user-select: auto !important; user-select: auto !important;
  283. }
  284. *:hover>img[src]{pointer-events:auto !important;}
  285.  
  286. [${$.utSelectionColorHack}] :not(input):not(textarea)::selection{ background-color: Highlight !important; color: HighlightText !important;}
  287. [${$.utSelectionColorHack}] :not(input):not(textarea)::-moz-selection{ background-color: Highlight !important; color: HighlightText !important;}
  288. [${$.utTapHighlight}] *{ -webkit-tap-highlight-color: rgba(0, 0, 0, 0.18) !important;}
  289.  
  290. html[${$.utLpSelection}] *:hover, html[${$.utLpSelection}] *:hover * { cursor:text !important;}
  291. html[${$.utLpSelection}] :not(input):not(textarea)::selection {background-color: rgba(255, 156, 179,0.5) !important;}
  292. html[${$.utLpSelection}] :not(input):not(textarea)::-moz-selection {background-color: rgba(255, 156, 179,0.5) !important;}
  293.  
  294. `.trim();
  295.  
  296. $.enableSelectClickCopy()
  297. $.createCSSElement(cssStyleOnReady, document.documentElement);
  298.  
  299. },
  300.  
  301. mainEvents: (listenerPress, listenerRelease) => {
  302. document.addEventListener("mousedown", listenerPress, true); // Capture Event; (desktop)
  303. document.addEventListener("contextmenu", listenerPress, true); // Capture Event; (desktop&mobile)
  304. document.addEventListener("mouseup", listenerRelease, false); // Bubble Event;
  305. }
  306.  
  307. }
  308.  
  309. $.mainEnableScript();
  310.  
  311. if (isSupportAdvancedEventListener()) $.lpEnable(); // top capture event for alt-click
  312.  
  313. $.mainEvents(
  314. function(evt) {
  315. if ($.onceCssHighlightSelection) window.requestAnimationFrame($.onceCssHighlightSelection);
  316. if (evt.button == 2 || evt.type == "contextmenu") $.mAlert_DOWN();
  317. },
  318. function(evt) {
  319. if (evt.button == 2) $.mAlert_UP();
  320. }
  321. );
  322.  
  323. console.log('userscript running - To Re-Enable Selection & Copying');
  324.  
  325. })();