RU AdList JS Fixes

try to take over the world!

目前為 2017-07-15 提交的版本,檢視 最新版本

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