RU AdList JS Fixes

try to take over the world!

当前为 2017-07-12 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name RU AdList JS Fixes
  3. // @namespace ruadlist_js_fixes
  4. // @version 20170712.0
  5. // @description try to take over the world!
  6. // @author lainverse & dimisa
  7. // @match *://*/*
  8. // @grant unsafeWindow
  9. // @grant window.clo1se
  10. // @grant GM_getValue
  11. // @grant GM_setValue
  12. // @grant GM_deleteValue
  13. // @run-at document-start
  14. // ==/UserScript==
  15.  
  16. (function() {
  17. 'use strict';
  18. let win = (unsafeWindow || window),
  19. // http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
  20. isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0,
  21. isChrome = !!window.chrome && !!window.chrome.webstore,
  22. isSafari = (Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0 ||
  23. (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window.safari || safari.pushNotification)),
  24. isFirefox = typeof InstallTrigger !== 'undefined',
  25. inIFrame = (win.self !== win.top),
  26. _getAttribute = Element.prototype.getAttribute,
  27. _setAttribute = Element.prototype.setAttribute,
  28. _de = document.documentElement,
  29. _appendChild = Document.prototype.appendChild.bind(_de),
  30. _removeChild = Document.prototype.removeChild.bind(_de),
  31. _createElement = Document.prototype.createElement.bind(document);
  32.  
  33. // NodeList iterator polyfill (mostly for Safari)
  34. // https://jakearchibald.com/2014/iterators-gonna-iterate/
  35. if (!NodeList.prototype[Symbol.iterator]) {
  36. NodeList.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
  37. }
  38.  
  39. // Options
  40. let opts = {
  41. 'useWSIFunc': useWSI
  42. };
  43.  
  44. {
  45. let optsCall = function(callback)
  46. {
  47. // Register event listener
  48. let key = "optsCallEvent_" + Math.random().toString(36).substr(2),
  49. cb = callback.func.bind(callback.name);
  50. window.addEventListener(key, cb, false);
  51. // Generate and dispatch synthetic event
  52. let ev = document.createEvent("HTMLEvents");
  53. ev.initEvent(key, true, false);
  54. window.dispatchEvent(ev);
  55. // Remove listener
  56. window.removeEventListener(key, cb, false);
  57. };
  58.  
  59. let initOptsHandler = function()
  60. {
  61. /*jshint validthis:true */
  62. opts[this] = GM_getValue(this, true);
  63. if (opts[this])
  64. opts[this+'Func']();
  65. };
  66.  
  67. optsCall({
  68. func: initOptsHandler,
  69. name: 'useWSI'
  70. });
  71.  
  72. // show options page
  73. let openOptions = function()
  74. {
  75. let ovl = _createElement('div'),
  76. inner = _createElement('div');
  77. ovl.style = (
  78. 'position: fixed;'+
  79. 'top:0; left:0;'+
  80. 'bottom: 0; right: 0;'+
  81. 'background: rgba(0,0,0,0.85);'+
  82. 'z-index: 2147483647;'+
  83. 'padding: 5em'
  84. );
  85. inner.style = (
  86. 'background: whitesmoke;'+
  87. 'font-size: 10pt;'+
  88. 'color: black;'+
  89. 'padding: 1em'
  90. );
  91. inner.textContent = 'JS Fixes Options: (reload page to apply)';
  92. inner.appendChild(_createElement('br'));
  93. inner.appendChild(_createElement('br'));
  94. ovl.addEventListener(
  95. 'click', function(e)
  96. {
  97. if (e.target === ovl) {
  98. ovl.parentNode.removeChild(ovl);
  99. e.preventDefault();
  100. }
  101. e.stopPropagation();
  102. }, false
  103. );
  104. // append checkbox with label function
  105. function addCheckbox(optName, optLabel)
  106. {
  107. let c = _createElement('input'),
  108. l = _createElement('label');
  109. c.type = 'checkbox';
  110. c.id = optName;
  111. optsCall({
  112. func: function()
  113. {
  114. c.checked = GM_getValue(this);
  115. },
  116. name: optName
  117. });
  118. c.addEventListener(
  119. 'click', function(e)
  120. {
  121. optsCall({
  122. func:function(){
  123. GM_setValue(this, e.target.checked);
  124. opts[this] = e.target.checked;
  125. },
  126. name:optName
  127. });
  128. }, true
  129. );
  130. l.textContent = optLabel;
  131. l.setAttribute('for', optName);
  132. inner.appendChild(c);
  133. inner.appendChild(l);
  134. inner.appendChild(_createElement('br'));
  135. }
  136. // append checkboxes
  137. addCheckbox('useWSI', 'Use WebSocket filter. Disable if experience problems with WebSocket connections.');
  138. document.body.appendChild(ovl);
  139. ovl.appendChild(inner);
  140. };
  141.  
  142. // monitor keys pressed for Ctrl+Alt+Shift+J > s > f code
  143. let opPos = 0, opKey = ['KeyJ','KeyS','KeyF'];
  144. document.addEventListener(
  145. 'keydown', function(e)
  146. {
  147. if ((e.code === opKey[opPos] || e.location) &&
  148. (!!opPos || e.altKey && e.ctrlKey && e.shiftKey))
  149. {
  150. opPos += e.location ? 0 : 1;
  151. e.stopPropagation();
  152. e.preventDefault();
  153. } else {
  154. opPos = 0;
  155. }
  156. if (opPos === opKey.length)
  157. {
  158. opPos = 0;
  159. openOptions();
  160. }
  161. }, false
  162. );
  163. }
  164.  
  165. // Special wrapper script to run scripts designed to override standard DOM functions
  166. // In Firefox appends supplied script to a page to make it run in page context and let
  167. // page content access overridden functions. In other browsers just run it as-is.
  168. function scriptLander(func, prepend)
  169. {
  170. if (!isFirefox)
  171. {
  172. func();
  173. return;
  174. }
  175. let script = _createElement('script');
  176. script.textContent = '(function(){let win=window;' + (
  177. prepend && prepend.join('') || ''
  178. ) + '!' + func + '();})();';
  179. _appendChild(script);
  180. _removeChild(script);
  181. }
  182.  
  183. // Creates and return protected style (unless protection is manually disabled).
  184. // Protected style will re-add itself on removal and remaind enabled on attempt to disable it.
  185. function createStyle(rules, props, skip_protect)
  186. {
  187. props = props || {};
  188. props.type = 'text/css';
  189.  
  190. function _protect(style)
  191. {
  192. if (skip_protect)
  193. return;
  194.  
  195. Object.defineProperty(style, 'sheet', {
  196. value: null,
  197. enumerable: true
  198. });
  199. Object.defineProperty(style, 'disabled', {
  200. get: () => true, //pretend to be disabled
  201. set: () => null,
  202. enumerable: true
  203. });
  204. (new MutationObserver(
  205. (ms) => _removeChild(ms[0].target)
  206. )).observe(style, { childList: true });
  207. }
  208.  
  209.  
  210. function _create()
  211. {
  212. let style = _appendChild(_createElement('style'));
  213. Object.assign(style, props);
  214.  
  215. function insertRules(rule)
  216. {
  217. if (rule.forEach)
  218. rule.forEach(insertRules);
  219. else try {
  220. style.sheet.insertRule(rule, 0);
  221. } catch (e) {
  222. console.error(e);
  223. }
  224. }
  225.  
  226. insertRules(rules);
  227. _protect(style);
  228.  
  229. return style;
  230. }
  231.  
  232. let style = _create();
  233. if (skip_protect)
  234. return style;
  235.  
  236. function resolveInANewContext(resolve)
  237. {
  238. setTimeout(
  239. (resolve) => resolve(_create()),
  240. 0, resolve
  241. );
  242. }
  243.  
  244. (new MutationObserver(
  245. function(ms)
  246. {
  247. let m, node;
  248. for (m of ms) for (node of m.removedNodes)
  249. if (node === style)
  250. (new Promise(resolveInANewContext))
  251. .then((st) => (style = st));
  252. }
  253. )).observe(_de, { childList: true });
  254.  
  255. return style;
  256. }
  257.  
  258. // https://greasyfork.org/scripts/19144-websuckit/
  259. function useWSI()
  260. {
  261. // check does browser support Proxy and WebSocket
  262. if (typeof Proxy !== 'function' ||
  263. typeof WebSocket !== 'function')
  264. return;
  265.  
  266. function getWrappedCode(removeSelf)
  267. {
  268. let text = getWrappedCode.toString() + WSI.toString();
  269. text = (
  270. '(function(){"use strict";'+
  271. text.replace(/\/\/[^\r\n]*/g,'').replace(/[\s\r\n]+/g,' ')+
  272. '(new WSI(self||window)).init();'+
  273. (removeSelf?'let s = document.currentScript; if (s) {s.parentNode.removeChild(s);}':'')+
  274. '})();\n'
  275. );
  276. return text;
  277. }
  278.  
  279. function WSI(win, safeWin)
  280. {
  281. safeWin = safeWin || win;
  282. let masks = [], filter;
  283. for (filter of [// blacklist
  284. '||185.87.50.147^',
  285. '||10root25.website^', '||24video.xxx^',
  286. '||adlabs.ru^', '||adspayformymortgage.win^', '||aviabay.ru^',
  287. '||bgrndi.com^', '||brokeloy.com^',
  288. '||cnamerutor.ru^',
  289. '||docfilms.info^', '||dreadfula.ru^',
  290. '||et-code.ru^',
  291. '||franecki.net^', '||film-doma.ru^',
  292. '||free-torrent.org^', '||free-torrent.pw^',
  293. '||free-torrents.org^', '||free-torrents.pw^',
  294. '||game-torrent.info^', '||gocdn.ru^',
  295. '||hdkinoshka.com^', '||hghit.com^', '||hindcine.net^',
  296. '||kiev.ua^', '||kinotochka.net^',
  297. '||kinott.com^', '||kinott.ru^', '||kuveres.com^',
  298. '||lepubs.com^', '||luxadv.com^', '||luxup.ru^', '||luxupcdna.com^',
  299. '||mail.ru^', '||marketgid.com^', '||mixadvert.com^', '||mxtads.com^',
  300. '||nickhel.com^',
  301. '||oconner.biz^', '||oconner.link^', '||octoclick.net^', '||octozoon.org^',
  302. '||pkpojhc.com^',
  303. '||psma01.com^', '||psma02.com^', '||psma03.com^',
  304. '||recreativ.ru^', '||redtram.com^', '||regpole.com^', '||rootmedia.ws^', '||ruttwind.com^',
  305. '||skidl.ru^',
  306. '||torvind.com^', '||traffic-media.co^', '||trafmag.com^',
  307. '||webadvert-gid.ru^', '||webadvertgid.ru^',
  308. '||xxuhter.ru^',
  309. '||yuiout.online^',
  310. '||zoom-film.ru^'])
  311. masks.push(new RegExp(
  312. filter.replace(/([\\\/\[\].*+?(){}$])/g, '\\$1')
  313. .replace(/\^(?!$)/g,'\\.?[^\\w%._-]')
  314. .replace(/\^$/,'\\.?([^\\w%._-]|$)')
  315. .replace(/^\|\|/,'^(ws|http)s?:\\/+([^\/.]+\\.)*'),
  316. 'i'));
  317.  
  318. function isBlocked(url) {
  319. for (let mask of masks)
  320. if (mask.test(url))
  321. return true;
  322. return false;
  323. }
  324.  
  325. let realWebSocket = win.WebSocket;
  326. function wsGetter(target, name)
  327. {
  328. try {
  329. if (typeof realWebSocket.prototype[name] === 'function')
  330. {
  331. if (name === 'close' || name === 'send') // send also closes connection
  332. target.readyState = realWebSocket.CLOSED;
  333. return (
  334. function fake() {
  335. console.log('[WSI] Invoked function "'+name+'"', '| Tracing', (new Error()));
  336. return;
  337. }
  338. );
  339. }
  340. if (typeof realWebSocket.prototype[name] === 'number')
  341. return realWebSocket[name];
  342. } catch(ignore) {}
  343. return target[name];
  344. }
  345.  
  346. function createWebSocketWrapper(target)
  347. {
  348. return new Proxy(realWebSocket, {
  349. construct: function (target, args)
  350. {
  351. let url = args[0];
  352. console.log('[WSI] Opening socket on ' + url + ' \u2026');
  353. if (isBlocked(url))
  354. {
  355. console.log("[WSI] Blocked.");
  356. return new Proxy({
  357. url: url,
  358. readyState: realWebSocket.OPEN
  359. }, {
  360. get: wsGetter,
  361. set: (val) => val
  362. });
  363. }
  364. return new target(args[0], args[1]);
  365. }
  366. });
  367. }
  368.  
  369. function WorkerWrapper()
  370. {
  371. let realWorker = win.Worker;
  372. win.Worker = function Worker() {
  373. let isBlobURL = /^blob:/i,
  374. resourceURI = arguments[0],
  375. deepLogMode = false,
  376. _callbacks = new WeakMap(),
  377. _worker = null,
  378. _onevs = { names: ['onmessage', 'onerror'] },
  379. _actions = [],
  380. /*jshint validthis:true */
  381. _self = this;
  382.  
  383. function log()
  384. {
  385. if (deepLogMode)
  386. console.log.apply(this, arguments);
  387. }
  388.  
  389. function callbackWrapper(func)
  390. {
  391. if (typeof func !== 'function')
  392. return undefined;
  393.  
  394. return function callback()
  395. {
  396. return func.apply(_self, arguments);
  397. };
  398. }
  399.  
  400. function updateWorker()
  401. {
  402. for (let [action, name, args] of _actions) {
  403. log(_worker, action, name, args);
  404. if (action === 'set')
  405. _worker[name] = callbackWrapper(args);
  406. if (action === 'call')
  407. _worker[name].apply(_worker, args);
  408. }
  409. _actions.length = 0;
  410. log('Applied buffered actions.');
  411. }
  412.  
  413. for (let prop of _onevs.names)
  414. Object.defineProperty(_self, prop, {
  415. set: function(val) {
  416. _onevs[prop] = val;
  417. if (_worker)
  418. _worker[prop] = callbackWrapper(val);
  419. else {
  420. _actions.push(['set', prop, val]);
  421. log('Stored into buffer:', arguments);
  422. }
  423. return val;
  424. },
  425. get: () => _onevs[prop],
  426. enumerable: true
  427. });
  428.  
  429. _self.postMessage = function()
  430. {
  431. if (_worker)
  432. _worker.postMessage.apply(_worker, arguments);
  433. else {
  434. _actions.push(['call', 'postMessage', arguments]);
  435. log('Stored into buffer:', arguments);
  436. }
  437. };
  438. _self.terminate = function()
  439. {
  440. if (_worker)
  441. _worker.terminate();
  442. else {
  443. _actions.push(['call','terminate', arguments]);
  444. log('Stored into buffer:', arguments);
  445. }
  446. };
  447. _self.addEventListener = function(event, callback, other)
  448. {
  449. if (typeof callback !== 'function')
  450. return;
  451.  
  452. if (!_callbacks.has(callback))
  453. _callbacks.set(callback, callbackWrapper(callback));
  454.  
  455. arguments[1] = _callbacks.get(callback);
  456. if (_worker)
  457. _worker.addEventListener.apply(_worker, arguments);
  458. else {
  459. _actions.push(['call', 'addEventListener', arguments]);
  460. log('Stored into buffer:', arguments);
  461. }
  462. };
  463. _self.removeEventListener = function(event, callback, other)
  464. {
  465. if (typeof callback !== 'function' || !_callbacks.has(callback))
  466. return;
  467.  
  468. arguments[1] = _callbacks.get(callback);
  469. _callbacks.delete(callback);
  470. if (_worker)
  471. _worker.removeEventListener.apply(_worker, arguments);
  472. else {
  473. _actions.push(['call', 'removeEventListener', arguments]);
  474. log('Stored into buffer:', arguments);
  475. }
  476. };
  477.  
  478. if (!isBlobURL.test(resourceURI))
  479. {
  480. _worker = new realWorker(resourceURI);
  481. return; // not a blob, no need to wrap
  482. }
  483.  
  484. (new Promise(
  485. function(resolve, reject)
  486. {
  487. let xhr = new XMLHttpRequest();
  488. xhr.responseType = 'blob';
  489. try {
  490. xhr.open('GET', resourceURI, true);
  491. } catch(e) {
  492. return reject(e);
  493. }
  494. if (xhr.readyState !== XMLHttpRequest.OPENED) {
  495. // connection wasn't opened, unable to continue wrapping procedure
  496. return reject(xhr.readyState);
  497. }
  498. xhr.onload = function(e)
  499. {
  500. if (e.target.status === 200)
  501. {
  502. let reader = new FileReader();
  503. reader.addEventListener(
  504. 'loadend', function(e)
  505. {
  506. resolve(
  507. new realWorker(URL.createObjectURL(
  508. new Blob([getWrappedCode(false) + e.target.result])
  509. ))
  510. );
  511. }, false
  512. );
  513. reader.readAsText(e.target.response);
  514. } else {
  515. return reject(e);
  516. }
  517. };
  518. xhr.onerror = (e) => reject(e);
  519. xhr.send();
  520. }
  521. )).then(
  522. function(val)
  523. {
  524. _worker = val;
  525. updateWorker();
  526. }
  527. ).catch(
  528. function(e)
  529. {
  530. // connection were blocked by CSP or something else triggered error event on xhr object
  531. // unable to proceed with wrapper, return object as-is
  532. _worker = new realWorker(resourceURI);
  533. updateWorker();
  534. }
  535. );
  536.  
  537. if (deepLogMode)
  538. {
  539. return new Proxy(_self, {
  540. get: function(target, prop) {
  541. console.log('Worker _get_', prop);
  542. return target[prop];
  543. },
  544. set: function(target, prop, val) {
  545. console.log('Worker _set_', prop, '_to_', val);
  546. target[prop] = val;
  547. return val;
  548. }
  549. });
  550. }
  551. }.bind(safeWin);
  552. }
  553.  
  554. function CreateElementWrapper()
  555. {
  556. let key = '_'+Math.random().toString(36).substr(2),
  557. _createElement = Document.prototype.createElement,
  558. _addEventListener = Element.prototype.addEventListener,
  559. isDataURL = /^data:/i,
  560. isBlobURL = /^blob:/i;
  561.  
  562. // IFrame SRC get/set wrapper
  563. let ifGetSet = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, 'src');
  564. if (ifGetSet)
  565. {
  566. let code = encodeURIComponent('<scr'+'ipt>'+getWrappedCode(true)+'</scr'+'ipt>\n'),
  567. dataSrc = new WeakMap(),
  568. _ifSet = ifGetSet.set,
  569. _ifGet = ifGetSet.get;
  570. ifGetSet.set = function(val)
  571. {
  572. if (this[key] && val === dataSrc.get(this))
  573. { // if already processed data URL then do nothing
  574. delete this[key];
  575. return null;
  576. }
  577. let isData = isDataURL.test(val);
  578. if (isData && val.indexOf(code) < 0)
  579. {
  580. dataSrc.set(this, val);
  581. val = val.replace(',',',' + code);
  582. }
  583. if (!isData && dataSrc.get(this))
  584. dataSrc.delete(this);
  585. return _ifSet.call(this, val);
  586. };
  587. ifGetSet.get = function()
  588. {
  589. return dataSrc.get(this) || _ifGet.call(this);
  590. };
  591. Object.defineProperty(HTMLIFrameElement.prototype, 'src', ifGetSet);
  592. }
  593.  
  594. function frameSetWSWrapper(e)
  595. {
  596. let frm = e.target;
  597. try {
  598. if (!frm.src || isBlobURL.test(frm.src))
  599. frm.contentWindow.WebSocket = createWebSocketWrapper();
  600. } catch (ignore) {}
  601. }
  602.  
  603. let scriptMap = new WeakMap();
  604. scriptMap.isBlocked = isBlocked;
  605. let onErrorWrapper = {
  606. set: function(val)
  607. {
  608. if (scriptMap.has(this))
  609. {
  610. this.removeEventListener('error', scriptMap.get(this).wrp, false);
  611. scriptMap.delete(this);
  612. }
  613. if (!val || typeof val !== 'function')
  614. return val;
  615.  
  616. scriptMap.set(this, {
  617. org: val,
  618. wrp: function()
  619. {
  620. if (scriptMap.isBlocked(this.src))
  621. console.log('[WSI] Blocked "onerror" callback from', this);
  622. else
  623. scriptMap.get(this).org.apply(this, arguments);
  624. }
  625. });
  626. this.addEventListener('error', scriptMap.get(this).wrp, false);
  627.  
  628. return val;
  629. },
  630. get: function()
  631. {
  632. return scriptMap.has(this) ? scriptMap.get(this).org : null;
  633. },
  634. enumerable: true
  635. };
  636. Document.prototype.createElement = function createElement(name) {
  637. /*jshint validthis:true */
  638. let el = _createElement.apply(this, arguments);
  639.  
  640. if (el.tagName === 'IFRAME')
  641. _addEventListener.call(el, 'load', frameSetWSWrapper, false);
  642. if (el.tagName === 'SCRIPT')
  643. Object.defineProperty(el, 'onerror', onErrorWrapper);
  644.  
  645. return el;
  646. };
  647.  
  648. document.addEventListener(
  649. 'DOMContentLoaded', function()
  650. {
  651. for (let ifr of document.querySelectorAll('IFRAME'))
  652. {
  653. if (isDataURL.test(ifr.src))
  654. {
  655. ifr[key] = true;
  656. ifr.src = ifr.src; // call setter and let it do the job
  657. }
  658. _addEventListener.call(ifr, 'load', frameSetWSWrapper, false);
  659. }
  660. }, false
  661. );
  662. }
  663.  
  664. this.init = function()
  665. {
  666. win.WebSocket = createWebSocketWrapper();
  667. if (!(/firefox/i.test(navigator.userAgent))) // skip WorkerWrapper in Firefox
  668. (new Promise(
  669. function(resolve, reject)
  670. { // test is it possible to run inline scripts
  671. if (self.constructor.name.indexOf('Worker') > -1)
  672. return resolve(); // running within a Worker
  673. let onerr = window.onerror,
  674. onscr = (e) => resolve();
  675. // for some reason addEventListener on 'error' doesn't catch this error
  676. window.onerror = (e) => reject(e);
  677. window.addEventListener('inlineSuccess', onscr, false);
  678. let scr = document.createElement('script');
  679. scr.textContent = "window.dispatchEvent(new Event('inlineSuccess'));";
  680. document.documentElement.appendChild(scr);
  681. document.documentElement.removeChild(scr);
  682. window.removeEventListener('inlineSuccess', onscr, false);
  683. window.onerror = onerr;
  684. }
  685. )).then(
  686. (e) => WorkerWrapper()
  687. ).catch(
  688. (e) => console.log('[WSI] Unable to create inline script. Skipping Worker wrapper to avoid further issues.', e)
  689. );
  690. if (typeof document !== 'undefined')
  691. CreateElementWrapper();
  692. };
  693. }
  694.  
  695. if (isFirefox)
  696. {
  697. let script = _createElement('script');
  698. script.textContent = getWrappedCode(true);
  699. _appendChild(script);
  700. _removeChild(script);
  701. return; //we don't want to call functions on page from here in Fx, so exit
  702. }
  703.  
  704. (new WSI((unsafeWindow||self||window),(self||window))).init();
  705. }
  706.  
  707. if (!isFirefox)
  708. { // scripts for non-Firefox browsers
  709.  
  710. // https://greasyfork.org/scripts/14720-it-s-not-important
  711. {
  712. let imptt = /((display|(margin|padding)(-top|-bottom)?)\s*:[^;!]*)!\s*important/ig,
  713. ret_b = (a,b) => b,
  714. _toLowerCase = String.prototype.toLowerCase,
  715. protectedNodes = new WeakSet(),
  716. log = false;
  717.  
  718. let logger = function()
  719. {
  720. if (log)
  721. console.log('Some page elements became a bit less important.');
  722. log = false;
  723. };
  724.  
  725. let unimportanter = function(node)
  726. {
  727. let style = (node.nodeType === Node.ELEMENT_NODE) ?
  728. _getAttribute.call(node, 'style') : null;
  729.  
  730. if (!style || !imptt.test(style) || node.style.display === 'none' ||
  731. (node.src && node.src.slice(0,17) === 'chrome-extension:')) // Web of Trust IFRAME and similar
  732. return false; // get out if we have nothing to do here
  733.  
  734. protectedNodes.add(node);
  735. _setAttribute.call(node, 'style',
  736. style.replace(imptt, ret_b));
  737. log = true;
  738. };
  739.  
  740. (new MutationObserver(
  741. function(mutations)
  742. {
  743. setTimeout(
  744. function(ms)
  745. {
  746. let m, node;
  747. for (m of ms) for (node of m.addedNodes)
  748. unimportanter(node);
  749. logger();
  750. }, 0, mutations
  751. );
  752. }
  753. )).observe(document, {
  754. childList : true,
  755. subtree : true
  756. });
  757.  
  758. Element.prototype.setAttribute = function setAttribute(name, value)
  759. {
  760. "[native code]";
  761. let replaced = value;
  762. if (_toLowerCase.call(name) === 'style' && protectedNodes.has(this))
  763. replaced = value.replace(imptt, ret_b);
  764. log = (replaced !== value);
  765. logger();
  766. return _setAttribute.call(this, name, replaced);
  767. };
  768.  
  769. win.addEventListener (
  770. 'load', function()
  771. {
  772. for (let imp of document.querySelectorAll('[style*="!"]'))
  773. unimportanter(imp);
  774. logger();
  775. }, false
  776. );
  777. }
  778.  
  779. }
  780.  
  781. if (/^https?:\/\/(mail\.yandex\.|music\.yandex\.|news\.yandex\.|(www\.)?yandex\.[^\/]+\/(yand)?search[\/?])/i.test(win.location.href))
  782. // https://greasyfork.org/en/scripts/809-no-yandex-ads
  783. document.addEventListener(
  784. 'DOMContentLoaded', function()
  785. {
  786. let adWords = [/Яндекс.Директ/i, /Реклама/i, /Ad/i],
  787. genericAdSelectors = (
  788. '.serp-adv__head + .serp-item,'+
  789. '#adbanner,'+
  790. '.serp-adv,'+
  791. '.b-spec-adv,'+
  792. 'div[class*="serp-adv__"]:not(.serp-adv__found):not(.serp-adv__displayed)'
  793. );
  794. // Generic ads removal and fixes
  795. {
  796. let node = document.querySelector('.serp-header');
  797. if (node)
  798. node.style.marginTop = '0';
  799. for (node of document.querySelectorAll(genericAdSelectors))
  800. remove(node);
  801. }
  802. // Short name for parentNode.removeChild
  803. function remove(node) {
  804. node.parentNode.removeChild(node);
  805. }
  806. // Search ads
  807. function removeSearchAds()
  808. {
  809. let node, subNode, content;
  810. for (node of document.querySelectorAll('.t-construct-adapter__legacy'))
  811. {
  812. subNode = node.querySelector('.organic__subtitle');
  813. if (subNode)
  814. content = window.getComputedStyle(subNode, ':after').content.replace(/"/g,'');
  815. if (subNode && content && adWords.map((expr)=>expr.test(content)).indexOf(true) > -1)
  816. {
  817. remove(node);
  818. console.log('Ads removed.');
  819. }
  820. }
  821. }
  822. // News ads
  823. function removeNewsAds()
  824. {
  825. for (let node of document.querySelectorAll(
  826. '.page-content__left > *,'+
  827. '.page-content__right > *:not(.page-content__col),'+
  828. '.page-content__right > .page-content__col > *'
  829. ))
  830. if (adWords[0].test(node.textContent) ||
  831. (node.clientHeight < 15 && s.classList.contains('rubric')))
  832. {
  833. remove(node);
  834. console.log('Ads removed.');
  835. }
  836. }
  837. // Music ads
  838. function removeMusicAds()
  839. {
  840. for (let node of document.querySelectorAll('.ads-block'))
  841. remove(node);
  842. }
  843. // Mail ads
  844. function removeMailAds()
  845. {
  846. let slice = Array.prototype.slice,
  847. nodes = slice.call(document.querySelectorAll('.ns-view-folders')),
  848. node, len, cls;
  849.  
  850. for (node of nodes)
  851. if (!len || len > node.classList.length)
  852. len = node.classList.length;
  853.  
  854. node = nodes.pop();
  855. while (node)
  856. {
  857. if (node.classList.length > len)
  858. for (cls of slice.call(node.classList))
  859. if (cls.indexOf('-') === -1)
  860. {
  861. remove(node);
  862. break;
  863. }
  864. node = nodes.pop();
  865. }
  866. }
  867. // News fixes
  868. function removePageAdsClass()
  869. {
  870. if (document.body.classList.contains("b-page_ads_yes"))
  871. {
  872. document.body.classList.remove("b-page_ads_yes");
  873. console.log('Page ads class removed.');
  874. }
  875. }
  876. // Function to attach an observer to monitor dynamic changes on the page
  877. function pageUpdateObserver(func, obj, params) {
  878. if (obj)
  879. (new MutationObserver(func))
  880. .observe(obj, (params || { childList:true, subtree:true }));
  881. }
  882.  
  883. if (win.location.hostname.search(/^mail\./i) === 0) {
  884. pageUpdateObserver(
  885. function(ms, o)
  886. {
  887. let aside = document.querySelector('.mail-Layout-Aside');
  888. if (aside) {
  889. o.disconnect();
  890. pageUpdateObserver(removeMailAds, aside);
  891. }
  892. }, document.body
  893. );
  894. removeMailAds();
  895. } else if (win.location.hostname.search(/^music\./i) === 0) {
  896. pageUpdateObserver(removeMusicAds, document.querySelector('.sidebar'));
  897. removeMusicAds();
  898. } else if (win.location.hostname.search(/^news\./i) === 0) {
  899. pageUpdateObserver(removeNewsAds, document.body);
  900. pageUpdateObserver(removePageAdsClass, document.body, { attributes:true, attributesFilter:['class'] });
  901. removeNewsAds();
  902. removePageAdsClass();
  903. } else {
  904. pageUpdateObserver(removeSearchAds, document.querySelector('.main__content'));
  905. removeSearchAds();
  906. }
  907. }
  908. );
  909. // Yandex Link Tracking
  910. if (/^https?:\/\/([^.]+\.)*yandex\.[^\/]+/i.test(win.location.href))
  911. {
  912. let fakeRoot = {
  913. appendChild: ()=>null,
  914. firstChild: null
  915. };
  916. Element.prototype.createShadowRoot = () => fakeRoot;
  917. Object.defineProperty(Element.prototype, "shadowRoot", {
  918. value: fakeRoot,
  919. enumerable: true,
  920. configurable: false
  921. });
  922. // Partially based on https://greasyfork.org/en/scripts/22737-remove-yandex-redirect
  923. let selectors = (
  924. 'A[onmousedown*="/jsredir"],'+
  925. 'A[data-vdir-href],'+
  926. 'A[data-counter]'
  927. );
  928. let removeTrackingAttributes = function(link)
  929. {
  930. link.removeAttribute('onmousedown');
  931. if (link.hasAttribute('data-vdir-href')) {
  932. link.removeAttribute('data-vdir-href');
  933. link.removeAttribute('data-orig-href');
  934. }
  935. if (link.hasAttribute('data-counter')) {
  936. link.removeAttribute('data-counter');
  937. link.removeAttribute('data-bem');
  938. }
  939. };
  940. let removeTracking = function(scope)
  941. {
  942. for (let link of scope.querySelectorAll(selectors))
  943. removeTrackingAttributes(link);
  944. };
  945. document.addEventListener('DOMContentLoaded', (e) => removeTracking(e.target));
  946. (new MutationObserver(
  947. function(ms)
  948. {
  949. let m, node;
  950. for (m of ms) for (node of m.addedNodes) if (node.nodeType === Node.ELEMENT_NODE)
  951. if (node.tagName === 'A' && node.matches(selectors)) {
  952. removeTrackingAttributes(node);
  953. } else {
  954. removeTracking(node);
  955. }
  956. }
  957. )).observe(_de, { childList: true, subtree: true });
  958.  
  959. //skip fixes for other sites
  960. return;
  961. }
  962.  
  963. // https://greasyfork.org/en/scripts/21937-moonwalk-hdgo-kodik-fix v0.8 (adapted)
  964. document.addEventListener(
  965. 'DOMContentLoaded', function()
  966. {
  967. function log (e) {
  968. console.log('Moonwalk&HDGo&Kodik FIX: ' + e + ' player in ' + win.location.href);
  969. }
  970. if (win.adv_enabled !== undefined && win.condition_detected !== undefined)
  971. {
  972. log('Moonwalk');
  973. if (win.adv_enabled)
  974. win.adv_enabled = false;
  975. win.condition_detected = false;
  976. if (win.MXoverrollCallback)
  977. document.addEventListener(
  978. 'click', function catcher(e)
  979. {
  980. e.stopPropagation();
  981. win.MXoverrollCallback.call(window);
  982. document.removeEventListener('click', catcher, true);
  983. }, true
  984. );
  985. }
  986. else if (win.stat_url !== undefined && win.is_html5 !== undefined && win.is_wp8 !== undefined)
  987. {
  988. log('HDGo');
  989. document.body.onclick = null;
  990. let tmp = document.querySelector('#swtf');
  991. if (tmp)
  992. tmp.style.display = 'none';
  993. if (win.banner_second !== undefined)
  994. win.banner_second = 0;
  995. if (win.$banner_ads !== undefined)
  996. win.$banner_ads = false;
  997. if (win.$new_ads !== undefined)
  998. win.$new_ads = false;
  999. if (win.createCookie !== undefined)
  1000. win.createCookie('popup', 'true', '999');
  1001. if (win.canRunAds !== undefined && win.canRunAds !== true)
  1002. win.canRunAds = true;
  1003. }
  1004. else if (win.MXoverrollCallback && win.iframeSearch !== undefined)
  1005. {
  1006. log('Kodik');
  1007. let tmp = document.querySelector('.play_button');
  1008. if (tmp)
  1009. tmp.onclick = win.MXoverrollCallback.bind(window);
  1010. win.IsAdBlock = false;
  1011. }
  1012. }, false
  1013. );
  1014.  
  1015. // Automated protection against specific circumvention method based on unwrapping various functions,
  1016. // hiding ads in the Shadow DOM and injecting iFrames with ads. Previously this code were known as
  1017. // apiBreaker since it were breaking Shadow DOM and onerror/onload API on specific domains. This
  1018. // version should be safe enough to run on majority of sites without actually breaking them.
  1019. scriptLander(
  1020. function()
  1021. {
  1022. let blacklist = new WeakMap();
  1023. /* Wrap functions used to attach shadow root to a node */
  1024. for (let func of ['createShadowRoot', 'attachShadow'])
  1025. if (func in Element.prototype)
  1026. Element.prototype[func] = (
  1027. (func) => function()
  1028. {
  1029. blacklist.set(this, true);
  1030. return func.apply(this, arguments);
  1031. }
  1032. )(Element.prototype[func]);
  1033.  
  1034. /* Wrap functions used to insert/append elements to check for IFRAME objects */
  1035. for (let func of [/*'appendChild', */'insertBefore'])
  1036. Object.defineProperty(
  1037. Element.prototype, func, {
  1038. enumerable: true,
  1039. value: (
  1040. (func) => function(el, par)
  1041. {
  1042. if (el.tagName === 'IFRAME' &&
  1043. (typeof par === 'object' && blacklist.get(par)))
  1044. {
  1045. console.log('Blocked suspicious', func.name, arguments);
  1046. return null;
  1047. }
  1048. return func.apply(this, arguments);
  1049. }
  1050. )(Element.prototype[func])
  1051. }
  1052. );
  1053. }
  1054. );
  1055.  
  1056. // === Helper functions ===
  1057.  
  1058. // function to search and remove nodes by content
  1059. // selector - standard CSS selector to define set of nodes to check
  1060. // words - regular expression to check content of the suspicious nodes
  1061. // params - object with multiple extra parameters:
  1062. // .log - display log in the console
  1063. // .hide - set display to none instead of removing from the page
  1064. // .parent - parent node to remove if content is found in the child node
  1065. // .siblings - number of simling nodes to remove (excluding text nodes)
  1066. let scRemove = (node) => node.parentNode.removeChild(node);
  1067. let scHide = function(node)
  1068. {
  1069. let style = _getAttribute.call(node, 'style') || '',
  1070. hide = ';display:none!important;';
  1071. if (style.indexOf(hide) < 0)
  1072. _setAttribute.call(node, 'style', style + hide);
  1073. };
  1074. function scissors (selector, words, scope, params)
  1075. {
  1076. if (params.log)
  1077. console.log('[s] starting with', selector, words, scope, JSON.stringify(params));
  1078. let remFunc = (params.hide ? scHide : scRemove),
  1079. iterFunc = (params.siblings > 0 ? 'nextSibling' : 'previousSibling'),
  1080. toRemove = [],
  1081. siblings;
  1082. for (let node of scope.querySelectorAll(selector))
  1083. {
  1084. if (params.log)
  1085. console.log('[s] found node', node);
  1086. if (params.parent)
  1087. {
  1088. while(node !== scope && !(node.matches(params.parent)))
  1089. node = node.parentNode;
  1090. if (params.log)
  1091. console.log('[s] moving to parent node', node);
  1092. if (node === scope)
  1093. {
  1094. if (params.log)
  1095. console.log('[s] reached scope node, nothing to remove here.');
  1096. break;
  1097. }
  1098. }
  1099. if (words.test(node.innerHTML) || !node.childNodes.length)
  1100. {
  1101. // drill up to the specified parent node if required
  1102. if (toRemove.indexOf(node) === -1)
  1103. {
  1104. if (params.log)
  1105. console.log('[s] adding node into list for removal');
  1106. toRemove.push(node);
  1107. // add multiple nodes if defined more than one sibling
  1108. siblings = Math.abs(params.siblings) || 0;
  1109. while (siblings)
  1110. {
  1111. node = node[iterFunc];
  1112. if (node.nodeType === Node.ELEMENT_NODE)
  1113. {
  1114. if (params.log)
  1115. console.log('[s] adding sibling node', node);
  1116. toRemove.push(node);
  1117. siblings -= 1; //count only element nodes
  1118. }
  1119. else if (!params.hide)
  1120. {
  1121. if (params.log)
  1122. console.log('[s] adding sibling node', node);
  1123. toRemove.push(node);
  1124. }
  1125. }
  1126. } else {
  1127. if (params.log)
  1128. console.log('[s] node already marked for removal');
  1129. }
  1130. } else {
  1131. if (params.log)
  1132. console.log('[s] word test failed, proceed to the next node');
  1133. }
  1134. }
  1135. if (params.log)
  1136. console.log('[s] proceeding with', (params.hide?'hide':'removal'), 'of', toRemove);
  1137. for (let node of toRemove)
  1138. remFunc(node);
  1139.  
  1140. return toRemove.length;
  1141. }
  1142.  
  1143. // function to perform multiple checks if ads inserted with a delay
  1144. // by default does 30 checks withing a 3 seconds unless nonstop mode specified
  1145. // also does 1 extra check when a page completely loads
  1146. // selector and words - passed dow to scissors
  1147. // params - object with multiple extra parameters:
  1148. // .log - display log in the console
  1149. // .root - selector to narrow down scope to scan;
  1150. // .observe - if true then check will be performed continuously;
  1151. // Other parameters passed down to scissors.
  1152. function gardener(selector, words, params)
  1153. {
  1154. params = params || {};
  1155. if (params.log)
  1156. console.log('[g] starting with', selector, words, JSON.stringify(params));
  1157. let scope = document,
  1158. nonstop = false;
  1159. // narrow down scope to a specific element
  1160. if (params.root)
  1161. {
  1162. scope = scope.querySelector(params.root);
  1163. if (!scope) // exit if the root element is not present on the page
  1164. return 0;
  1165. if (params.log)
  1166. console.log('[g] scope', scope);
  1167. }
  1168. // add observe mode if required
  1169. if (params.observe)
  1170. {
  1171. if (typeof MutationObserver === 'function')
  1172. {
  1173. (new MutationObserver(
  1174. function(ms)
  1175. {
  1176. for (let m of ms) if (m.addedNodes.length)
  1177. scissors(selector, words, scope, params);
  1178. }
  1179. )).observe(scope, { childList:true, subtree: true });
  1180. if (params.log)
  1181. console.log('[g] observer enabled');
  1182. } else {
  1183. nonstop = true;
  1184. if (params.log)
  1185. console.log('[g] nonstop mode enabled');
  1186. }
  1187. }
  1188. // wait for a full page load to do one extra cut
  1189. win.addEventListener(
  1190. 'load', function()
  1191. {
  1192. if (params.log)
  1193. console.log('[g] onload cleanup');
  1194. scissors(selector, words, scope, params);
  1195. }
  1196. );
  1197. // do multiple cuts during page load until ads removed
  1198. function cut(sci, s, w, sc, p, i)
  1199. {
  1200. if (i > 0)
  1201. i -= 1;
  1202. if (i && !sci(s, w, sc, p))
  1203. setTimeout(cut, 100, sci, s, w, sc, p, i);
  1204. }
  1205. cut(scissors, selector, words, scope, params, (nonstop ? -1 : 30));
  1206. }
  1207.  
  1208. // Helper function to close background tab if site opens itself in a new tab and then
  1209. // loads a 3rd-party page in the background one (thus performing background redirect).
  1210. function preventBackgroundRedirect()
  1211. {
  1212. // create "cose_me" event to call high-level window.close()
  1213. let key = Math.random().toString(36).substr(2);
  1214. window.addEventListener('close_me_' + key, () => window.close());
  1215.  
  1216. // window.open wrapper
  1217. function pbrLander()
  1218. {
  1219. let _open = window.open,
  1220. idx = String.prototype.indexOf,
  1221. event = new CustomEvent("close_me_%key%", {});
  1222. // site went to a new tab and attempts to unload
  1223. // call for high-level close through event
  1224. let closeWindow = () => window.dispatchEvent(event);
  1225.  
  1226. // window.open wrapper
  1227. window.open = function open()
  1228. {
  1229. console.log(arguments, window.location.host);
  1230. if (arguments[0] &&
  1231. (idx.call(arguments[0], window.location.host) > -1 ||
  1232. idx.call(arguments[0], '://') === -1))
  1233. window.addEventListener('unload', closeWindow, true);
  1234. _open.apply(window, arguments);
  1235. }.bind(window);
  1236.  
  1237. // Node.createElement wrapper to prevent click-dispatch in Google Chrome and similar browsers
  1238. let _createElement = Document.prototype.createElement;
  1239. Document.prototype.createElement = function createElement(name)
  1240. {
  1241. /*jshint validthis:true */
  1242. let el = _createElement.apply(this, arguments);
  1243. if (el.tagName === 'A')
  1244. el.addEventListener(
  1245. 'click', function(e)
  1246. {
  1247. if (!e.target.parentNode || !e.isTrusted)
  1248. window.addEventListener('unload', closeWindow, true);
  1249. }, false
  1250. );
  1251. return el;
  1252. };
  1253. console.log("Background redirect prevention enabled.");
  1254. }
  1255.  
  1256. // land wrapper on the page
  1257. let script = document.createElement('script');
  1258. script.textContent = '('+pbrLander.toString().replace(/%key%/g,key)+')();';
  1259. _appendChild(script);
  1260. _removeChild(script);
  1261. }
  1262.  
  1263. // Function to catch and block various methods to open a new window with 3rd-party content.
  1264. // Some advertisement networks went way past simple window.open call to circumvent default popup protection.
  1265. // This funciton blocks window.open, ability to restore original window.open from an IFRAME object,
  1266. // ability to perform an untrusted (not initiated by user) click on a link, click on a link without a parent
  1267. // node or simply a link with piece of javascript code in the HREF attribute.
  1268. function preventPopups()
  1269. {
  1270. if (inIFrame)
  1271. {
  1272. let i = -1, val;
  1273. do {
  1274. i++;
  1275. val = GM_getValue('forbid.popups.' + i);
  1276. } while(val & val !== win.location.href);
  1277. GM_setValue('forbid.popups.' + i, win.location.href);
  1278. win.top.postMessage('forbid.popups.' + i, '*');
  1279. return;
  1280. }
  1281.  
  1282. scriptLander(
  1283. function()
  1284. {
  1285. let _createElement = Document.prototype.createElement,
  1286. _appendChild = Element.prototype.appendChild;
  1287.  
  1288. function open()
  1289. {
  1290. '[native code]';
  1291. console.log('Site attempted to open a new window', arguments);
  1292. return {
  1293. document: {
  1294. write: () => {},
  1295. writeln: () => {}
  1296. }
  1297. };
  1298. }
  1299.  
  1300. function redefineOpen(obj)
  1301. {
  1302. Object.defineProperty(obj, 'open', {
  1303. get: () => open,
  1304. set: (val) => val,
  1305. enumerable: true
  1306. });
  1307. }
  1308. redefineOpen(win);
  1309.  
  1310. Document.prototype.createElement = function createElement(name)
  1311. {
  1312. /*jshint validthis:true */
  1313. let el = _createElement.apply(this, arguments);
  1314. if (el.tagName === 'A')
  1315. el.addEventListener(
  1316. 'click', function(e)
  1317. {
  1318. if (!e.target.parentNode || !e.isTrusted ||
  1319. (e.target.href && e.target.href.toLowerCase().indexOf('javascript') > -1))
  1320. {
  1321. e.preventDefault();
  1322. console.log('Blocked suspicious click event', e, 'on', e.target);
  1323. }
  1324. }, false
  1325. );
  1326. if (el.tagName === 'IFRAME')
  1327. el.addEventListener(
  1328. 'load', function(e)
  1329. {
  1330. try {
  1331. redefineOpen(e.target.contentWindow);
  1332. } catch(ignore) {}
  1333. }, false
  1334. );
  1335. return el;
  1336. };
  1337.  
  1338. Element.prototype.appendChild = function appendChild()
  1339. {
  1340. /*jshint validthis:true */
  1341. let el = _appendChild.apply(this, arguments);
  1342. if (el && el.nodeType === Node.ELEMENT_NODE && el.tagName === 'IFRAME') {
  1343. try {
  1344. redefineOpen(el.contentWindow);
  1345. } catch(ignore) {}
  1346. }
  1347. return el;
  1348. };
  1349. console.log('Popup prevention enabled.');
  1350. }
  1351. );
  1352. }
  1353. // External listener for case when site known to open popups were loaded in iframe
  1354. // It will sandbox any iframe which will send message 'forbid.popups' (preventPopups sends it)
  1355. // Some sites replace frame's window.location with data-url to run in clean context
  1356. if (!inIFrame)
  1357. {
  1358. let popWindows = new WeakSet();
  1359. window.addEventListener(
  1360. 'message', function(e)
  1361. {
  1362. if (typeof e.data === "string" && e.data.slice(0,13) === 'forbid.popups' &&
  1363. !popWindows.has(e.source))
  1364. {
  1365. let src = GM_getValue(e.data);
  1366. if (src)
  1367. GM_deleteValue(e.data);
  1368. popWindows.add(e.source); // remember window of iframe with suspected domain
  1369. for (let frame of document.querySelectorAll('iframe'))
  1370. if (frame.contentWindow === e.source)
  1371. {
  1372. if (frame.hasAttribute('sandbox'))
  1373. // remove allow-popups if frame already sandboxed
  1374. frame.sandbox.remove('allow-popups');
  1375. else
  1376. // set sandbox mode for troublesome frame and allow scripts and forms
  1377. frame.setAttribute('sandbox','allow-forms allow-scripts');
  1378. console.log('Disallowed popups from iframe', frame);
  1379.  
  1380. // reload frame content to apply restrictions
  1381. if (!src) {
  1382. src = frame.src;
  1383. console.log('Unable to get current iframe location, reloading from src', src);
  1384. } else
  1385. console.log('Reloading iframe with URL', src);
  1386. frame.src = 'about:blank';
  1387. frame.src = src;
  1388. }
  1389. }
  1390. }, false
  1391. );
  1392. }
  1393.  
  1394. // Currently unused piece of code developed to prevent site from registering serviceWorker
  1395. // and uninstall any existing instances of serivceWorker in case there is one already.
  1396. /* Commented out since not used
  1397. function forbidServiceWorker()
  1398. {
  1399. if (!("serviceWorker" in navigator))
  1400. return;
  1401. let svr = navigator.serviceWorker.ready;
  1402. Object.defineProperty(navigator, 'serviceWorker', {
  1403. value: {
  1404. register: function()
  1405. {
  1406. console.log('Registration of serviceWorker ' + arguments[0] + ' blocked.');
  1407. return new Promise(function(){});
  1408. },
  1409. ready: new Promise(() => null),
  1410. addEventListener: () => null
  1411. }
  1412. });
  1413. document.addEventListener(
  1414. 'DOMContentLoaded', function()
  1415. {
  1416. if (!svr)
  1417. return;
  1418. svr.then(
  1419. function(sw)
  1420. {
  1421. console.log('Found existing serviceWorker:', sw);
  1422. console.log('Attempting to unregister...');
  1423. sw.unregister().then(
  1424. () => console.log('Done.')
  1425. ).catch(
  1426. function(err)
  1427. {
  1428. console.log('Unregistration failed. :(', err);
  1429. console.log('Try to remove it manually:');
  1430. console.log(' 1. Open: chrome://serviceworker-internals/ (Google Chrome and alike) or about:serviceworkers (Mozilla Firefox) in a new tab.');
  1431. console.log(' 2. Search there for one with "'+document.domain+'" in the name.');
  1432. console.log(' 3. Use buttons in the same block with service you found to stop it and uninstall/unregister.');
  1433. }
  1434. );
  1435. }
  1436. ).catch(
  1437. (e) => console.log("LOL, existing serviceWorker failed on it's own! -_-", e)
  1438. );
  1439. }, false
  1440. );
  1441. }
  1442. /**/
  1443.  
  1444. // Currently obsolete code developed to prevent error and load calls on objects supposed to load resources
  1445. // from the internet like IMG or IFRAME, but missing SRC/HREF attribute. Usually tricks like this are used
  1446. // to unwrap wrapped functions to be able to load ads.
  1447. /* Commented out since not used
  1448. function errorAndLoadEventsFilter()
  1449. {
  1450. let toString = Function.prototype.toString,
  1451. _addEventListener = Element.prototype.addEventListener,
  1452. _removeEventListener = Element.prototype.removeEventListener,
  1453. hasAttribute = Element.prototype.hasAttribute,
  1454. evtMap = new WeakMap();
  1455. Element.prototype.addEventListener = function addEventListener(evt, func, capt) {
  1456. if ((evt === 'error' || evt === 'load') && !evtMap.get(func))
  1457. {
  1458. evtMap.set(
  1459. func, function()
  1460. {
  1461. if (hasAttribute.call(this, 'src') ||
  1462. hasAttribute.call(this, 'href'))
  1463. func.apply(this, arguments);
  1464. else
  1465. console.log('Blocked', evt, 'handler', toString.call(func), 'on', this);
  1466. }
  1467. );
  1468. }
  1469. _addEventListener.call(this, evt, (evtMap.get(func) || func), capt);
  1470. };
  1471. Element.prototype.removeEventListener = function removeEventListener(evt, func, capt) {
  1472. _removeEventListener.call(this, evt, (evtMap.get(func) || func), capt);
  1473. };
  1474. Object.defineProperty(HTMLElement.prototype, 'onload', {
  1475. set: function(func)
  1476. {
  1477. if(evtMap.has(this)) {
  1478. if (evtMap.get(this).onload)
  1479. _removeEventListener.call(this, 'load', evtMap.get(this).onload, false);
  1480. evtMap.get(this).onload = func;
  1481. } else
  1482. evtMap.set(this, { onload: func });
  1483.  
  1484. if (func)
  1485. _addEventListener.call(this, 'load', func, false);
  1486.  
  1487. return func;
  1488. },
  1489. get: function()
  1490. {
  1491. return evtMap.has(this) ? evtMap.get(this).onload : null;
  1492. }
  1493. });
  1494. Object.defineProperty(HTMLElement.prototype, 'onerror', {
  1495. set: function(func)
  1496. {
  1497. if (evtMap.has(this))
  1498. evtMap.get(this).onerror = func;
  1499. else
  1500. evtMap.set(this, { onerror: func });
  1501.  
  1502. if (func)
  1503. console.log('Blocked error handler', toString.call(func), 'on', this);
  1504.  
  1505. return func;
  1506. },
  1507. get: function()
  1508. {
  1509. return evtMap.has(this) ? evtMap.get(this).onerror : null;
  1510. }
  1511. });
  1512. }
  1513. /**/
  1514.  
  1515. // === Scripts for specific domains ===
  1516.  
  1517. let scripts = {};
  1518. // prevent popups and redirects block
  1519. // Popups
  1520. scripts.preventPopups = {
  1521. other: [
  1522. 'biqle.ru',
  1523. 'chaturbate.com',
  1524. 'dfiles.ru',
  1525. 'hentaiz.org',
  1526. 'mirrorcreator.com',
  1527. 'online-multy.ru', 'openload.co',
  1528. 'radikal.ru',
  1529. 'seedoff.cc', 'seedoff.tv',
  1530. 'tapochek.net', 'thepiratebay.org', 'torseed.net',
  1531. 'unionpeer.com',
  1532. 'zippyshare.com'
  1533. ],
  1534. now: preventPopups
  1535. };
  1536. // Background redirects
  1537. scripts.preventBackgroundRedirect = {
  1538. other: [
  1539. 'mediafire.com', 'megapeer.org', 'megapeer.ru',
  1540. 'perfectgirls.net',
  1541. 'turbobit.net'
  1542. ],
  1543. now: preventBackgroundRedirect
  1544. };
  1545.  
  1546. // other
  1547. scripts['4pda.ru'] = {
  1548. now: function()
  1549. {
  1550. // https://greasyfork.org/en/scripts/14470-4pda-unbrender
  1551. let hStyle,
  1552. isForum = document.location.href.search('/forum/') !== -1,
  1553. remove = (node) => (node ? node.parentNode.removeChild(node) : null),
  1554. afterClean = () => remove(hStyle);
  1555.  
  1556. function beforeClean()
  1557. {
  1558. // attach styles before document displayed
  1559. hStyle = createStyle([
  1560. 'html { overflow-y: scroll }',
  1561. 'section[id] {'+(
  1562. 'position: absolute;'+
  1563. 'width: 100%'
  1564. )+'}',
  1565. 'article + aside * { display: none !important }',
  1566. '#header + div:after {'+(
  1567. 'content: "";'+
  1568. 'position: fixed;'+
  1569. 'top: 0;'+
  1570. 'left: 0;'+
  1571. 'width: 100%;'+
  1572. 'height: 100%;'+
  1573. 'background-color: #E6E7E9'
  1574. )+'}',
  1575. // http://codepen.io/Beaugust/pen/DByiE
  1576. '@keyframes spin { 100% { transform: rotate(360deg) } }',
  1577. 'article + aside:after {'+(
  1578. 'content: "";'+
  1579. 'position: absolute;'+
  1580. 'width: 150px;'+
  1581. 'height: 150px;'+
  1582. 'top: 150px;'+
  1583. 'left: 50%;'+
  1584. 'margin-top: -75px;'+
  1585. 'margin-left: -75px;'+
  1586. 'box-sizing: border-box;'+
  1587. 'border-radius: 100%;'+
  1588. 'border: 10px solid rgba(0, 0, 0, 0.2);'+
  1589. 'border-top-color: rgba(0, 0, 0, 0.6);'+
  1590. 'animation: spin 2s infinite linear'
  1591. )+'}'
  1592. ], {id:'ubrHider'}, true);
  1593.  
  1594. // display content of a page if time to load a page is more than 2 seconds to avoid
  1595. // blocking access to a page if it is loading for too long or stuck in a loading state
  1596. setTimeout(2000, afterClean);
  1597. }
  1598.  
  1599. createStyle([
  1600. '#nav .use-ad { display: block !important }',
  1601. 'article:not(.post) + article:not(#id),'+
  1602. 'html:not(#id)>body:not(#id) a[target="_blank"] img[height="90"] { display: none !important }'
  1603. ]);
  1604.  
  1605. if (!isForum)
  1606. beforeClean();
  1607.  
  1608. // save links to non-overridden functions to use later
  1609. let protectedElems;
  1610. // protect/hide changed attributes in case site attempt to restore them
  1611. function styleProtector(eventMode)
  1612. {
  1613. let _toLowerCase = String.prototype.toLowerCase,
  1614. isStyleText = (t) => (_toLowerCase.call(t) === 'style'),
  1615. protectedElems = new WeakMap();
  1616. function protoOverride(element, functionName, isStyleCheck, returnIfProtected)
  1617. {
  1618. let originalFunction = element.prototype[functionName];
  1619. element.prototype[functionName] = function wrapper()
  1620. {
  1621. if (protectedElems.has(this) && isStyleCheck(arguments[0]))
  1622. return returnIfProtected(this, arguments);
  1623. return originalFunction.apply(this, arguments);
  1624. };
  1625. }
  1626. protoOverride(Element, 'removeAttribute', isStyleText, () => undefined);
  1627. protoOverride(Element, 'hasAttribute', isStyleText, (_this) => protectedElems.get(_this) !== null);
  1628. protoOverride(Element, 'setAttribute', isStyleText, (_this, args) => protectedElems.set(_this, args[1]));
  1629. protoOverride(Element, 'getAttribute', isStyleText, (_this) => protectedElems.get(_this));
  1630. if (!eventMode)
  1631. return protectedElems;
  1632. else
  1633. {
  1634. let e = document.createEvent('Event');
  1635. e.initEvent('protoOverride', false, false);
  1636. window.protectedElems = protectedElems;
  1637. window.dispatchEvent(e);
  1638. }
  1639. }
  1640. if (!isFirefox)
  1641. protectedElems = styleProtector(false);
  1642. else
  1643. {
  1644. let script = document.createElement('script');
  1645. script.textContent = '(' + styleProtector.toString() + ')(true);';
  1646. window.addEventListener(
  1647. 'protoOverride', function protoOverrideCallback(e)
  1648. {
  1649. if (win.protectedElems) {
  1650. protectedElems = win.protectedElems;
  1651. delete win.protectedElems;
  1652. }
  1653. document.removeEventListener('protoOverride', protoOverrideCallback, true);
  1654. }, true
  1655. );
  1656. _appendChild(script);
  1657. _removeChild(script);
  1658. }
  1659.  
  1660. // clean a page
  1661. window.addEventListener(
  1662. 'DOMContentLoaded', function()
  1663. {
  1664. let width = () => window.innerWidth || _de.clientWidth || document.body.clientWidth || 0;
  1665. let height = () => window.innerHeight || _de.clientHeight || document.body.clientHeight || 0;
  1666.  
  1667. if (isForum)
  1668. {
  1669. let si = document.querySelector('#logostrip');
  1670. if (si)
  1671. remove(si.parentNode.nextSibling);
  1672. }
  1673.  
  1674. if (document.location.href.search('/forum/dl/') !== -1) {
  1675. document.body.setAttribute('style', (document.body.getAttribute('style')||'')+
  1676. ';background-color:black!important');
  1677. for (let itm of document.querySelectorAll('body>div'))
  1678. if (!itm.querySelector('.dw-fdwlink'))
  1679. remove(itm);
  1680. }
  1681.  
  1682. if (isForum) // Do not continue if it's a forum
  1683. return;
  1684.  
  1685. {
  1686. let si = document.querySelector('#header');
  1687. if (si)
  1688. {
  1689. let rem = si.previousSibling;
  1690. while (rem)
  1691. {
  1692. si = rem.previousSibling;
  1693. remove(rem);
  1694. rem = si;
  1695. }
  1696. }
  1697. }
  1698.  
  1699. for (let itm of document.querySelectorAll('#nav li[class]'))
  1700. if (itm && itm.querySelector('a[href^="/tag/"]'))
  1701. remove(itm);
  1702.  
  1703. let style, result,
  1704. fakeStyles = new WeakMap(),
  1705. styleProxy = {
  1706. get: function(target, prop)
  1707. {
  1708. let fakeStyle = fakeStyles.get(target);
  1709. return ((prop in fakeStyle) ? fakeStyle : target)[prop];
  1710. },
  1711. set: function(target, prop, value)
  1712. {
  1713. let fakeStyle = fakeStyles.get(target);
  1714. ((prop in fakeStyle) ? fakeStyle : target)[prop] = value;
  1715. return value;
  1716. }
  1717. };
  1718. for (let itm of document.querySelectorAll('DIV, A'))
  1719. {
  1720. if (itm.tagName ==='DIV' &&
  1721. itm.offsetWidth > 0.95 * width() &&
  1722. itm.offsetHeight > 0.85 * height())
  1723. {
  1724. style = window.getComputedStyle(itm, null);
  1725. result = [];
  1726.  
  1727. if (style.backgroundImage !== 'none')
  1728. result.push('background-image:none!important');
  1729.  
  1730. if (style.backgroundColor !== 'transparent' &&
  1731. style.backgroundColor !== 'rgba(0, 0, 0, 0)')
  1732. result.push('background-color:transparent!important');
  1733.  
  1734. if (result.length)
  1735. {
  1736. if (itm.getAttribute('style'))
  1737. result.unshift(itm.getAttribute('style'));
  1738.  
  1739. fakeStyles.set(itm.style, {
  1740. 'backgroundImage': itm.style.backgroundImage,
  1741. 'backgroundColor': itm.style.backgroundColor
  1742. });
  1743.  
  1744. try {
  1745. Object.defineProperty(itm, 'style', {
  1746. value: new Proxy(itm.style, styleProxy),
  1747. enumerable: true
  1748. });
  1749. } catch (e) {
  1750. console.log('Unable to protect style property.', e);
  1751. }
  1752.  
  1753. if (protectedElems)
  1754. protectedElems.set(itm, _getAttribute.call(itm, 'style'));
  1755.  
  1756. _setAttribute.call(itm, 'style', result.join(';'));
  1757. }
  1758. }
  1759. if (itm.tagName ==='A' &&
  1760. (itm.offsetWidth > 0.95 * width() ||
  1761. itm.offsetHeight > 0.85 * height()))
  1762. {
  1763. if (protectedElems)
  1764. protectedElems.set(itm, _getAttribute.call(itm, 'style'));
  1765.  
  1766. _setAttribute.call(itm, 'style', 'display:none!important');
  1767. }
  1768. }
  1769.  
  1770. for (let itm of document.querySelectorAll('ASIDE>DIV'))
  1771. if ( ((itm.querySelector('script, iframe, a[href*="/ad/www/"]') ||
  1772. itm.querySelector('img[src$=".gif"]:not([height="0"]), img[height="400"]')) &&
  1773. !itm.classList.contains('post') ) || !itm.childNodes.length )
  1774. remove(itm);
  1775.  
  1776. document.body.setAttribute('style', (document.body.getAttribute('style')||'')+';background-color:#E6E7E9!important');
  1777.  
  1778. // display content of the page
  1779. afterClean();
  1780. }
  1781. );
  1782. }
  1783. };
  1784.  
  1785. scripts['allmovie.pro'] = {
  1786. other: ['rufilmtv.org'],
  1787. dom: function()
  1788. {
  1789. // pretend to be Android to make site use different played for ads
  1790. if (isSafari)
  1791. return;
  1792. Object.defineProperty(navigator, 'userAgent', {
  1793. get: function(){ return 'Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19'; },
  1794. enumerable: true
  1795. });
  1796. }
  1797. };
  1798.  
  1799. scripts['anidub-online.ru'] = {
  1800. other: ['online.anidub.com'],
  1801. dom: function()
  1802. {
  1803. if (win.ogonekstart1)
  1804. win.ogonekstart1 = () => console.log("Fire in the hole!");
  1805. },
  1806. now: () => createStyle([
  1807. '.background {background: none!important;}',
  1808. '.background > script + div,'+
  1809. '.background > script ~ div:not([id]):not([class]) + div[id][class]'+
  1810. '{display:none!important}'
  1811. ])
  1812. };
  1813.  
  1814. scripts['drive2.ru'] = () => gardener('.c-block:not([data-metrika="recomm"]),.o-grid__item', />Реклама<\//i);
  1815.  
  1816. scripts['fishki.net'] = () => gardener('.drag_list > .drag_element, .list-view > .paddingtop15, .post-wrap', /543769|Новости\sпартнеров/);
  1817.  
  1818. scripts['gidonline.club'] = {
  1819. now: () => createStyle('.tray > div[style] {display: none!important}')
  1820. };
  1821.  
  1822. scripts['hdgo.cc'] = {
  1823. other: ['46.30.43.38', 'couber.be'],
  1824. now: () => (new MutationObserver(
  1825. function(ms)
  1826. {
  1827. let m, node;
  1828. for (m of ms) for (node of m.addedNodes)
  1829. if (node.tagName === 'SCRIPT' && _getAttribute.call(node, 'onerror') !== null)
  1830. node.removeAttribute('onerror');
  1831. }
  1832. )).observe(document, { childList:true, subtree: true })
  1833. };
  1834.  
  1835. scripts['gismeteo.ru'] = {
  1836. other: ['gismeteo.ua'],
  1837. dom: () => gardener('div > a[target^="_"]', /Яндекс\.Директ/i, { root: 'body', observe: true, parent: 'div[class*="frame"]'})
  1838. };
  1839.  
  1840. scripts['hdrezka.me'] = {
  1841. now: function()
  1842. {
  1843. Object.defineProperty(win, 'fuckAdBlock', {
  1844. value: { onDetected: () => console.log('Pretending to be an ABP detector.') },
  1845. enumerable: true
  1846. });
  1847. Object.defineProperty(win, 'ab', {
  1848. value: false,
  1849. enumerable: true
  1850. });
  1851. },
  1852. dom: () => gardener('div[id][onclick][onmouseup][onmousedown]', /onmouseout/i)
  1853. };
  1854.  
  1855. scripts['imageban.ru'] = {
  1856. now: preventBackgroundRedirect,
  1857. dom: () => win.addEventListener(
  1858. 'unload', function()
  1859. {
  1860. window.location.hash = 'x'+Math.random().toString(36).substr(2);
  1861. }, true
  1862. )
  1863. };
  1864.  
  1865. scripts['mail.ru'] = {
  1866. // Trick to prevent mail.ru from removing 3rd-party styles
  1867. now: () => scriptLander(
  1868. () => Object.defineProperty(Object.prototype, 'restoreVisibility', {
  1869. get: () => (() => null),
  1870. set: () => null
  1871. })
  1872. )
  1873. };
  1874.  
  1875. scripts['megogo.net'] = {
  1876. now: function()
  1877. {
  1878. Object.defineProperty(win, "adBlock", {
  1879. get: () => false,
  1880. set: () => null,
  1881. enumerable : true
  1882. });
  1883. Object.defineProperty(win, "showAdBlockMessage", {
  1884. get: () => (() => null),
  1885. set: () => null,
  1886. enumerable: true
  1887. });
  1888. }
  1889. };
  1890.  
  1891. scripts['naruto-base.su'] = () => gardener('div[id^="entryID"],.block', /href="http.*?target="_blank"/i);
  1892.  
  1893. scripts['overclockers.ru'] = {
  1894. now: function()
  1895. {
  1896. createStyle('.fixoldhtml {display:block!important}');
  1897. if (!isChrome && !isOpera)
  1898. return; // Looks like my code works only in Chrome-like browsers
  1899. let noContentYet = true;
  1900. function jWrap()
  1901. {
  1902. let _$ = win.$, _e = _$.extend;
  1903. win.$ = function()
  1904. {
  1905. let _ret = _$.apply(window, arguments);
  1906. if (_ret[0] === document.body)
  1907. _ret.html = () => console.log('Anti-adblock prevented.');
  1908. return _ret;
  1909. };
  1910. win.$.extend = function()
  1911. {
  1912. return _e.apply(_$, arguments);
  1913. };
  1914. win.jQuery = win.$;
  1915. }
  1916. (function jReady()
  1917. {
  1918. if (!win.$ && noContentYet)
  1919. setTimeout(jReady, 0);
  1920. else
  1921. jWrap();
  1922. })();
  1923. document.addEventListener ('DOMContentLoaded', () => (noContentYet = false), false);
  1924. }
  1925. };
  1926. scripts['forums.overclockers.ru'] = {
  1927. now: function()
  1928. {
  1929. createStyle('.needblock {position: fixed; left: -10000px}');
  1930. Object.defineProperty(win, 'adblck', {
  1931. get: () => 'no',
  1932. set: () => null,
  1933. enumerable: true
  1934. });
  1935. }
  1936. };
  1937.  
  1938. scripts['pb.wtf'] = {
  1939. other: ['piratbit.org', 'piratbit.ru'],
  1940. dom: function()
  1941. {
  1942. createStyle('.reques,#result,tbody.row1:not([id]) {display: none !important}');
  1943. // image in the slider in the header
  1944. gardener('a[href^="/ex"],a[href$="=="]', /img/i, {root:'.release-navbar', observe:true, parent:'div'});
  1945. // ads in blocks on the page
  1946. gardener('a[href^="/topic/234257"]', /Как\sразместить/i, {siblings:-1, root:'#main_content', observe:true, parent:'span[style]'});
  1947. // line above topic content
  1948. gardener('.re_top1', /./, {root:'#main_content', parent:'.hidden-sm'});
  1949. }
  1950. };
  1951.  
  1952. scripts['pikabu.ru'] = () => gardener('.story', /story__sponsor|story__gag|profile\/ads"/i, {root: '.inner_wrap', observe: true});
  1953.  
  1954. scripts['qrz.ru'] = {
  1955. now: function()
  1956. {
  1957. Object.defineProperty(win, 'ab', {
  1958. get:()=>false,
  1959. set:()=>null
  1960. });
  1961. Object.defineProperty(win, 'tryMessage', {
  1962. get:()=>(()=>null),
  1963. set:()=>null
  1964. });
  1965. }
  1966. };
  1967.  
  1968. scripts['razlozhi.ru'] = {
  1969. now: function()
  1970. {
  1971. for (let func of ['createShadowRoot', 'attachShadow'])
  1972. if (func in Element.prototype)
  1973. Element.prototype[func] = function(){ return this.cloneNode(); };
  1974. }
  1975. };
  1976.  
  1977. scripts['rp5.ru'] = {
  1978. other: ['rp5.by', 'rp5.kz', 'rp5.ua'],
  1979. dom: function()
  1980. {
  1981. createStyle('#bannerBottom {display: none!important}');
  1982. let co = document.querySelector('#content');
  1983. if (!co)
  1984. return;
  1985. let nodes = co.parentNode.childNodes,
  1986. i = nodes.length;
  1987. while (i--)
  1988. if (nodes[i] !== co)
  1989. nodes[i].parentNode.removeChild(nodes[i]);
  1990. }
  1991. };
  1992.  
  1993. scripts['rustorka.com'] = {
  1994. other: ['rumedia.ws'],
  1995. now: function()
  1996. {
  1997. createStyle('.header > div:not(.head-block) a, #sidebar1 img, #logo img {opacity:0!important}', {
  1998. id: 'tempHidingStyles'
  1999. }, true);
  2000. preventPopups();
  2001. },
  2002. dom: function()
  2003. {
  2004. for (let o of document.querySelectorAll('IMG, A'))
  2005. if ((o.clientWidth === 728 && o.clientHeight === 90) ||
  2006. (o.clientWidth === 300 && o.clientHeight === 250))
  2007. {
  2008. while (o && o.tagName !== 'A')
  2009. o = o.parentNode;
  2010. if (o)
  2011. _setAttribute.call(o, 'style', 'display: none !important');
  2012. }
  2013. let s = document.querySelector('#tempHidingStyles');
  2014. s.parentNode.removeChild(s);
  2015. }
  2016. };
  2017.  
  2018. scripts['sport-express.ru'] = () => gardener('.js-relap__item',/>Реклама\s+<\//, {root:'.container', observe: true});
  2019.  
  2020. scripts['sports.ru'] = function()
  2021. {
  2022. gardener('.aside-news-list__item', /aside-news-list__advert/i, {root:'.columns-layout__left', observe: true});
  2023. gardener('.material-list__item', /Реклама/i, {root:'.columns-layout', observe: true});
  2024. // extra functionality: shows/hides panel at the top depending on scroll direction
  2025. createStyle([
  2026. '.user-panel__fixed { transition: top 0.2s ease-in-out!important; }',
  2027. '.user-panel-up { top: -40px!important }'
  2028. ], {id: 'userPanelSlide'}, false);
  2029. (function lookForPanel()
  2030. {
  2031. let panel = document.querySelector('.user-panel__fixed');
  2032. if (!panel)
  2033. setTimeout(lookForPanel, 100);
  2034. else
  2035. window.addEventListener(
  2036. 'wheel', function(e)
  2037. {
  2038. if (e.deltaY > 0 && !panel.classList.contains('user-panel-up'))
  2039. panel.classList.add('user-panel-up');
  2040. else if (e.deltaY < 0 && panel.classList.contains('user-panel-up'))
  2041. panel.classList.remove('user-panel-up');
  2042. }, false
  2043. );
  2044. })();
  2045. };
  2046.  
  2047. scripts['vk.com'] = () => gardener('div[data-post-id]', /wall_marked_as_ads/, {root: '#page_wall_posts', observe: true});
  2048.  
  2049. scripts['yap.ru'] = {
  2050. other: ['yaplakal.com'],
  2051. dom: function()
  2052. {
  2053. gardener('form > table[id^="p_row_"]:nth-of-type(2)', /member1438|Administration/);
  2054. gardener('.icon-comments', /member1438|Administration|\/go\/\?http/, {parent:'tr', siblings:-2});
  2055. }
  2056. };
  2057.  
  2058. scripts['rambler.ru'] = {
  2059. other: ['championat.ru','gazeta.ru','lenta.ru'],
  2060. now: () => scriptLander(
  2061. function()
  2062. {
  2063. let _createElement = Document.prototype.createElement,
  2064. loadMap = new WeakMap();
  2065. Document.prototype.createElement = function createElement(name) {
  2066. /*jshint validthis:true */
  2067. let el = _createElement.apply(this, arguments);
  2068. if (el.tagName !== 'LINK')
  2069. return el;
  2070. Object.defineProperty(el, 'onload', {
  2071. get: function() {
  2072. return loadMap.get(loadMap.get(this));
  2073. },
  2074. set: function(func) {
  2075. let wrap = loadMap.get(this),
  2076. isContent = /\{\s*content\s*:\s*"[^"]+"/i;
  2077. if (wrap)
  2078. {
  2079. this.removeEventListener('load', wrap, false);
  2080. loadMap.remove(wrap);
  2081. loadMap.remove(this);
  2082. }
  2083. wrap = function(e)
  2084. {
  2085. if (e.target && e.target.sheet && e.target.sheet.cssRules &&
  2086. e.target.sheet.cssRules[0] && e.target.sheet.cssRules[0].cssText &&
  2087. isContent.test(e.target.sheet.cssRules[0].cssText))
  2088. {
  2089. console.log('Blocked "onload" for', e.target.href);
  2090. return false;
  2091. }
  2092. return func.apply(this, arguments);
  2093. };
  2094. loadMap.set(this, wrap);
  2095. loadMap.set(wrap, func);
  2096. this.addEventListener('load', wrap, false);
  2097. },
  2098. enumberable: true
  2099. });
  2100. return el;
  2101. };
  2102. }
  2103. )
  2104. };
  2105.  
  2106. scripts['reactor.cc'] = {
  2107. other: ['joyreactor.cc', 'pornreactor.cc'],
  2108. now: function()
  2109. {
  2110. win.open = (function(){ throw new Error('Redirect prevention.'); }).bind(window);
  2111. },
  2112. click: function(e)
  2113. {
  2114. let node = e.target;
  2115. if (node.nodeType === Node.ELEMENT_NODE &&
  2116. node.style.position === 'absolute' &&
  2117. node.style.zIndex > 0)
  2118. node.parentNode.removeChild(node);
  2119. },
  2120. dom: function()
  2121. {
  2122. let words = new RegExp(
  2123. 'блокировщика рекламы'
  2124. .split('')
  2125. .map(function(e){return e+'[\u200b\u200c\u200d]*';})
  2126. .join('')
  2127. .replace(' ', '\\s*')
  2128. .replace(/[аоре]/g, function(e){return ['[аa]','[оo]','[рp]','[еe]']['аоре'.indexOf(e)];}),
  2129. 'i'),
  2130. can;
  2131. function deeper(spider)
  2132. {
  2133. let c, l, n;
  2134. if (words.test(spider.innerText))
  2135. {
  2136. if (spider.nodeType === Node.TEXT_NODE)
  2137. return true;
  2138. c = spider.childNodes;
  2139. l = c.length;
  2140. n = 0;
  2141. while(l--)
  2142. if (deeper(c[l]), can)
  2143. n++;
  2144. if (n > 0 && n === c.length && spider.offsetHeight < 750)
  2145. can.push(spider);
  2146. return false;
  2147. }
  2148. return true;
  2149. }
  2150. function probe()
  2151. {
  2152. if (words.test(document.body.innerText))
  2153. {
  2154. can = [];
  2155. deeper(document.body);
  2156. let i = can.length, spider;
  2157. while(i--) {
  2158. spider = can[i];
  2159. if (spider.offsetHeight > 10 && spider.offsetHeight < 750)
  2160. _setAttribute.call(spider, 'style', 'background:none!important');
  2161. }
  2162. }
  2163. }
  2164. (new MutationObserver(probe))
  2165. .observe(document, { childList:true, subtree:true });
  2166. }
  2167. };
  2168.  
  2169. scripts['auto.ru'] = function()
  2170. {
  2171. let words = /Реклама|Яндекс.Директ|yandex_ad_/;
  2172. let userAdsListAds = (
  2173. '.listing-list > .listing-item,'+
  2174. '.listing-item_type_fixed.listing-item'
  2175. );
  2176. let catalogAds = (
  2177. 'div[class*="layout_catalog-inline"],'+
  2178. 'div[class$="layout_horizontal"]'
  2179. );
  2180. let otherAds = (
  2181. '.advt_auto,'+
  2182. '.sidebar-block,'+
  2183. '.pager-listing + div[class],'+
  2184. '.card > div[class][style],'+
  2185. '.sidebar > div[class],'+
  2186. '.main-page__section + div[class],'+
  2187. '.listing > tbody'
  2188. );
  2189. gardener(userAdsListAds, words, {root:'.listing-wrap', observe:true});
  2190. gardener(catalogAds, words, {root:'.catalog__page,.content__wrapper', observe:true});
  2191. gardener(otherAds, words);
  2192. };
  2193.  
  2194. scripts['rsload.net'] = {
  2195. load: function()
  2196. {
  2197. let dis = document.querySelector('label[class*="cb-disable"]');
  2198. if (dis)
  2199. dis.click();
  2200. },
  2201. click: function(e)
  2202. {
  2203. let t = e.target;
  2204. if (t && t.href && (/:\/\/\d+\.\d+\.\d+\.\d+\//.test(t.href)))
  2205. t.href = t.href.replace('://','://rsload.net:rsload.net@');
  2206. }
  2207. };
  2208.  
  2209. let domain, name;
  2210. // add alternate domain names if present
  2211. for (name in scripts) if (scripts[name].other)
  2212. for (domain of scripts[name].other) if (!(domain in scripts))
  2213. scripts[domain] = scripts[name];
  2214. // look for current domain in the list and run appropriate code
  2215. domain = document.domain;
  2216. while (domain.indexOf('.') > -1)
  2217. {
  2218. if (domain in scripts)
  2219. {
  2220. if (typeof scripts[domain] === 'function')
  2221. {
  2222. document.addEventListener ('DOMContentLoaded', scripts[domain], false);
  2223. break;
  2224. }
  2225. for (name in scripts[domain])
  2226. switch(name)
  2227. {
  2228. case 'other':
  2229. break;
  2230. case 'now':
  2231. scripts[domain][name]();
  2232. break;
  2233. case 'load':
  2234. window.addEventListener('load', scripts[domain][name], false);
  2235. break;
  2236. case 'dom':
  2237. document.addEventListener('DOMContentLoaded', scripts[domain][name], false);
  2238. break;
  2239. default:
  2240. document.addEventListener (name, scripts[domain][name], false);
  2241. }
  2242. }
  2243. domain = domain.slice(domain.indexOf('.') + 1);
  2244. }
  2245. })();