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