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.4
  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. nullStr = {
  860. get: () => '',
  861. set: (x) => x
  862. };
  863. Object.defineProperties(style, {
  864. innerHTML: nullStr,
  865. textContent: nullStr
  866. });
  867. Object.defineProperties(style.sheet, {
  868. deleteRule: () => null,
  869. cssRules: emptyArr,
  870. rules: emptyArr
  871. });
  872. }
  873. ).catch(
  874. ()=>console.log("Can't protect ABP's style element.")
  875. );
  876. let _removeChild = Node.prototype.removeChild;
  877. Node.prototype.removeChild = function(child)
  878. {
  879. if (child === style)
  880. return;
  881. return _removeChild.apply(this, arguments);
  882. };
  883. }
  884. }
  885.  
  886. if (/^https?:\/\/(mail\.yandex\.|music\.yandex\.|news\.yandex\.|(www\.)?yandex\.[^\/]+\/(yand)?search[\/?])/i.test(win.location.href))
  887. // https://greasyfork.org/en/scripts/809-no-yandex-ads
  888. document.addEventListener(
  889. 'DOMContentLoaded', function()
  890. {
  891. let adWords = [/Яндекс.Директ/i, /Реклама/i, /Ad/i],
  892. genericAdSelectors = (
  893. '.serp-adv__head + .serp-item,'+
  894. '#adbanner,'+
  895. '.serp-adv,'+
  896. '.b-spec-adv,'+
  897. 'div[class*="serp-adv__"]:not(.serp-adv__found):not(.serp-adv__displayed)'
  898. );
  899. // Generic ads removal and fixes
  900. {
  901. let node = document.querySelector('.serp-header');
  902. if (node)
  903. node.style.marginTop = '0';
  904. for (node of document.querySelectorAll(genericAdSelectors))
  905. remove(node);
  906. }
  907. // Short name for parentNode.removeChild
  908. function remove(node) {
  909. node.parentNode.removeChild(node);
  910. }
  911. // Search ads
  912. function removeSearchAds()
  913. {
  914. let node, subNode, content;
  915. for (node of document.querySelectorAll('.t-construct-adapter__legacy'))
  916. {
  917. subNode = node.querySelector('.organic__subtitle');
  918. if (subNode)
  919. content = window.getComputedStyle(subNode, ':after').content.replace(/"/g,'');
  920. if (subNode && content && adWords.map((expr)=>expr.test(content)).indexOf(true) > -1)
  921. {
  922. remove(node);
  923. console.log('Ads removed.');
  924. }
  925. }
  926. }
  927. // News ads
  928. function removeNewsAds()
  929. {
  930. for (let node of document.querySelectorAll(
  931. '.page-content__left > *,'+
  932. '.page-content__right > *:not(.page-content__col),'+
  933. '.page-content__right > .page-content__col > *'
  934. ))
  935. if (adWords[0].test(node.textContent) ||
  936. (node.clientHeight < 15 && s.classList.contains('rubric')))
  937. {
  938. remove(node);
  939. console.log('Ads removed.');
  940. }
  941. }
  942. // Music ads
  943. function removeMusicAds()
  944. {
  945. for (let node of document.querySelectorAll('.ads-block'))
  946. remove(node);
  947. }
  948. // Mail ads
  949. function removeMailAds()
  950. {
  951. let slice = Array.prototype.slice,
  952. nodes = slice.call(document.querySelectorAll('.ns-view-folders')),
  953. node, len, cls;
  954.  
  955. for (node of nodes)
  956. if (!len || len > node.classList.length)
  957. len = node.classList.length;
  958.  
  959. node = nodes.pop();
  960. while (node)
  961. {
  962. if (node.classList.length > len)
  963. for (cls of slice.call(node.classList))
  964. if (cls.indexOf('-') === -1)
  965. {
  966. remove(node);
  967. break;
  968. }
  969. node = nodes.pop();
  970. }
  971. }
  972. // News fixes
  973. function removePageAdsClass()
  974. {
  975. if (document.body.classList.contains("b-page_ads_yes"))
  976. {
  977. document.body.classList.remove("b-page_ads_yes");
  978. console.log('Page ads class removed.');
  979. }
  980. }
  981. // Function to attach an observer to monitor dynamic changes on the page
  982. function pageUpdateObserver(func, obj, params) {
  983. if (obj)
  984. (new MutationObserver(func))
  985. .observe(obj, (params || { childList:true, subtree:true }));
  986. }
  987.  
  988. if (win.location.hostname.search(/^mail\./i) === 0) {
  989. pageUpdateObserver(
  990. function(ms, o)
  991. {
  992. let aside = document.querySelector('.mail-Layout-Aside');
  993. if (aside) {
  994. o.disconnect();
  995. pageUpdateObserver(removeMailAds, aside);
  996. }
  997. }, document.body
  998. );
  999. removeMailAds();
  1000. } else if (win.location.hostname.search(/^music\./i) === 0) {
  1001. pageUpdateObserver(removeMusicAds, document.querySelector('.sidebar'));
  1002. removeMusicAds();
  1003. } else if (win.location.hostname.search(/^news\./i) === 0) {
  1004. pageUpdateObserver(removeNewsAds, document.body);
  1005. pageUpdateObserver(removePageAdsClass, document.body, { attributes:true, attributesFilter:['class'] });
  1006. removeNewsAds();
  1007. removePageAdsClass();
  1008. } else {
  1009. pageUpdateObserver(removeSearchAds, document.querySelector('.main__content'));
  1010. removeSearchAds();
  1011. }
  1012. }
  1013. );
  1014.  
  1015. // Yandex Link Tracking
  1016. if (/^https?:\/\/([^.]+\.)*yandex\.[^\/]+/i.test(win.location.href))
  1017. {
  1018. let fakeRoot = {
  1019. appendChild: ()=>null,
  1020. firstChild: null
  1021. };
  1022. Element.prototype.createShadowRoot = () => fakeRoot;
  1023. Object.defineProperty(Element.prototype, "shadowRoot", {
  1024. value: fakeRoot,
  1025. enumerable: true,
  1026. configurable: false
  1027. });
  1028. // Partially based on https://greasyfork.org/en/scripts/22737-remove-yandex-redirect
  1029. let selectors = (
  1030. 'A[onmousedown*="/jsredir"],'+
  1031. 'A[data-vdir-href],'+
  1032. 'A[data-counter]'
  1033. );
  1034. let removeTrackingAttributes = function(link)
  1035. {
  1036. link.removeAttribute('onmousedown');
  1037. if (link.hasAttribute('data-vdir-href')) {
  1038. link.removeAttribute('data-vdir-href');
  1039. link.removeAttribute('data-orig-href');
  1040. }
  1041. if (link.hasAttribute('data-counter')) {
  1042. link.removeAttribute('data-counter');
  1043. link.removeAttribute('data-bem');
  1044. }
  1045. };
  1046. let removeTracking = function(scope)
  1047. {
  1048. for (let link of scope.querySelectorAll(selectors))
  1049. removeTrackingAttributes(link);
  1050. };
  1051. document.addEventListener('DOMContentLoaded', (e) => removeTracking(e.target));
  1052. (new MutationObserver(
  1053. function(ms)
  1054. {
  1055. let m, node;
  1056. for (m of ms) for (node of m.addedNodes) if (node.nodeType === Node.ELEMENT_NODE)
  1057. if (node.tagName === 'A' && node.matches(selectors)) {
  1058. removeTrackingAttributes(node);
  1059. } else {
  1060. removeTracking(node);
  1061. }
  1062. }
  1063. )).observe(_de, { childList: true, subtree: true });
  1064.  
  1065. //skip fixes for other sites
  1066. return;
  1067. }
  1068.  
  1069. // https://greasyfork.org/en/scripts/21937-moonwalk-hdgo-kodik-fix v0.8 (adapted)
  1070. document.addEventListener(
  1071. 'DOMContentLoaded', function()
  1072. {
  1073. function log (e) {
  1074. console.log('Moonwalk&HDGo&Kodik FIX: ' + e + ' player in ' + win.location.href);
  1075. }
  1076. if (win.adv_enabled !== undefined && win.condition_detected !== undefined)
  1077. {
  1078. log('Moonwalk');
  1079. if (win.adv_enabled)
  1080. win.adv_enabled = false;
  1081. win.condition_detected = false;
  1082. if (win.MXoverrollCallback)
  1083. document.addEventListener(
  1084. 'click', function catcher(e)
  1085. {
  1086. e.stopPropagation();
  1087. win.MXoverrollCallback.call(window);
  1088. document.removeEventListener('click', catcher, true);
  1089. }, true
  1090. );
  1091. }
  1092. else if (win.stat_url !== undefined && win.is_html5 !== undefined && win.is_wp8 !== undefined)
  1093. {
  1094. log('HDGo');
  1095. document.body.onclick = null;
  1096. let tmp = document.querySelector('#swtf');
  1097. if (tmp)
  1098. tmp.style.display = 'none';
  1099. if (win.banner_second !== undefined)
  1100. win.banner_second = 0;
  1101. if (win.$banner_ads !== undefined)
  1102. win.$banner_ads = false;
  1103. if (win.$new_ads !== undefined)
  1104. win.$new_ads = false;
  1105. if (win.createCookie !== undefined)
  1106. win.createCookie('popup', 'true', '999');
  1107. if (win.canRunAds !== undefined && win.canRunAds !== true)
  1108. win.canRunAds = true;
  1109. }
  1110. else if (win.MXoverrollCallback && win.iframeSearch !== undefined)
  1111. {
  1112. log('Kodik');
  1113. let tmp = document.querySelector('.play_button');
  1114. if (tmp)
  1115. tmp.onclick = win.MXoverrollCallback.bind(window);
  1116. win.IsAdBlock = false;
  1117. }
  1118. }, false
  1119. );
  1120.  
  1121. // Automated protection against specific circumvention method based on unwrapping various functions,
  1122. // hiding ads in the Shadow DOM and injecting iFrames with ads. Previously this code were known as
  1123. // apiBreaker since it were breaking Shadow DOM and onerror/onload API on specific domains. This
  1124. // version should be safe enough to run on majority of sites without actually breaking them.
  1125. scriptLander(
  1126. function()
  1127. {
  1128. let blacklist = new WeakMap();
  1129. /* Wrap functions used to attach shadow root to a node */
  1130. for (let func of ['createShadowRoot', 'attachShadow'])
  1131. if (func in Element.prototype)
  1132. Element.prototype[func] = (
  1133. (func) => function()
  1134. {
  1135. blacklist.set(this, true);
  1136. return func.apply(this, arguments);
  1137. }
  1138. )(Element.prototype[func]);
  1139.  
  1140. /* Wrap functions used to insert/append elements to check for IFRAME objects */
  1141. for (let func of [/*'appendChild', */'insertBefore'])
  1142. Object.defineProperty(
  1143. Element.prototype, func, {
  1144. enumerable: true,
  1145. value: (
  1146. (func) => function(el, par)
  1147. {
  1148. if (el.tagName === 'IFRAME' &&
  1149. (typeof par === 'object' && blacklist.get(par)))
  1150. {
  1151. console.log('Blocked suspicious', func.name, arguments);
  1152. return null;
  1153. }
  1154. return func.apply(this, arguments);
  1155. }
  1156. )(Element.prototype[func])
  1157. }
  1158. );
  1159. }
  1160. );
  1161.  
  1162. // === Helper functions ===
  1163.  
  1164. // function to search and remove nodes by content
  1165. // selector - standard CSS selector to define set of nodes to check
  1166. // words - regular expression to check content of the suspicious nodes
  1167. // params - object with multiple extra parameters:
  1168. // .log - display log in the console
  1169. // .hide - set display to none instead of removing from the page
  1170. // .parent - parent node to remove if content is found in the child node
  1171. // .siblings - number of simling nodes to remove (excluding text nodes)
  1172. let scRemove = (node) => node.parentNode.removeChild(node);
  1173. let scHide = function(node)
  1174. {
  1175. let style = _getAttribute.call(node, 'style') || '',
  1176. hide = ';display:none!important;';
  1177. if (style.indexOf(hide) < 0)
  1178. _setAttribute.call(node, 'style', style + hide);
  1179. };
  1180. function scissors (selector, words, scope, params)
  1181. {
  1182. if (params.log)
  1183. console.log('[s] starting with', selector, words, scope, JSON.stringify(params));
  1184. let remFunc = (params.hide ? scHide : scRemove),
  1185. iterFunc = (params.siblings > 0 ? 'nextSibling' : 'previousSibling'),
  1186. toRemove = [],
  1187. siblings;
  1188. for (let node of scope.querySelectorAll(selector))
  1189. {
  1190. if (params.log)
  1191. console.log('[s] found node', node);
  1192. if (params.parent)
  1193. {
  1194. while(node !== scope && !(node.matches(params.parent)))
  1195. node = node.parentNode;
  1196. if (params.log)
  1197. console.log('[s] moving to parent node', node);
  1198. if (node === scope)
  1199. {
  1200. if (params.log)
  1201. console.log('[s] reached scope node, nothing to remove here.');
  1202. break;
  1203. }
  1204. }
  1205. if (words.test(node.innerHTML) || !node.childNodes.length)
  1206. {
  1207. // drill up to the specified parent node if required
  1208. if (toRemove.indexOf(node) === -1)
  1209. {
  1210. if (params.log)
  1211. console.log('[s] adding node into list for removal');
  1212. toRemove.push(node);
  1213. // add multiple nodes if defined more than one sibling
  1214. siblings = Math.abs(params.siblings) || 0;
  1215. while (siblings)
  1216. {
  1217. node = node[iterFunc];
  1218. if (node.nodeType === Node.ELEMENT_NODE)
  1219. {
  1220. if (params.log)
  1221. console.log('[s] adding sibling node', node);
  1222. toRemove.push(node);
  1223. siblings -= 1; //count only element nodes
  1224. }
  1225. else if (!params.hide)
  1226. {
  1227. if (params.log)
  1228. console.log('[s] adding sibling node', node);
  1229. toRemove.push(node);
  1230. }
  1231. }
  1232. } else {
  1233. if (params.log)
  1234. console.log('[s] node already marked for removal');
  1235. }
  1236. } else {
  1237. if (params.log)
  1238. console.log('[s] word test failed, proceed to the next node');
  1239. }
  1240. }
  1241. if (params.log)
  1242. console.log('[s] proceeding with', (params.hide?'hide':'removal'), 'of', toRemove);
  1243. for (let node of toRemove)
  1244. remFunc(node);
  1245.  
  1246. return toRemove.length;
  1247. }
  1248.  
  1249. // function to perform multiple checks if ads inserted with a delay
  1250. // by default does 30 checks withing a 3 seconds unless nonstop mode specified
  1251. // also does 1 extra check when a page completely loads
  1252. // selector and words - passed dow to scissors
  1253. // params - object with multiple extra parameters:
  1254. // .log - display log in the console
  1255. // .root - selector to narrow down scope to scan;
  1256. // .observe - if true then check will be performed continuously;
  1257. // Other parameters passed down to scissors.
  1258. function gardener(selector, words, params)
  1259. {
  1260. params = params || {};
  1261. if (params.log)
  1262. console.log('[g] starting with', selector, words, JSON.stringify(params));
  1263. let scope = document,
  1264. nonstop = false;
  1265. // narrow down scope to a specific element
  1266. if (params.root)
  1267. {
  1268. scope = scope.querySelector(params.root);
  1269. if (!scope) // exit if the root element is not present on the page
  1270. return 0;
  1271. if (params.log)
  1272. console.log('[g] scope', scope);
  1273. }
  1274. // add observe mode if required
  1275. if (params.observe)
  1276. {
  1277. if (typeof MutationObserver === 'function')
  1278. {
  1279. (new MutationObserver(
  1280. function(ms)
  1281. {
  1282. for (let m of ms) if (m.addedNodes.length)
  1283. scissors(selector, words, scope, params);
  1284. }
  1285. )).observe(scope, { childList:true, subtree: true });
  1286. if (params.log)
  1287. console.log('[g] observer enabled');
  1288. } else {
  1289. nonstop = true;
  1290. if (params.log)
  1291. console.log('[g] nonstop mode enabled');
  1292. }
  1293. }
  1294. // wait for a full page load to do one extra cut
  1295. win.addEventListener(
  1296. 'load', function()
  1297. {
  1298. if (params.log)
  1299. console.log('[g] onload cleanup');
  1300. scissors(selector, words, scope, params);
  1301. }
  1302. );
  1303. // do multiple cuts during page load until ads removed
  1304. function cut(sci, s, w, sc, p, i)
  1305. {
  1306. if (i > 0)
  1307. i -= 1;
  1308. if (i && !sci(s, w, sc, p))
  1309. setTimeout(cut, 100, sci, s, w, sc, p, i);
  1310. }
  1311. cut(scissors, selector, words, scope, params, (nonstop ? -1 : 30));
  1312. }
  1313.  
  1314. // Helper function to close background tab if site opens itself in a new tab and then
  1315. // loads a 3rd-party page in the background one (thus performing background redirect).
  1316. function preventBackgroundRedirect()
  1317. {
  1318. // create "cose_me" event to call high-level window.close()
  1319. let key = Math.random().toString(36).substr(2);
  1320. window.addEventListener('close_me_' + key, () => window.close());
  1321.  
  1322. // window.open wrapper
  1323. function pbrLander()
  1324. {
  1325. let _open = window.open,
  1326. idx = String.prototype.indexOf,
  1327. event = new CustomEvent("close_me_%key%", {});
  1328. // site went to a new tab and attempts to unload
  1329. // call for high-level close through event
  1330. let closeWindow = () => window.dispatchEvent(event);
  1331.  
  1332. // window.open wrapper
  1333. window.open = function open()
  1334. {
  1335. console.log(arguments, window.location.host);
  1336. if (arguments[0] &&
  1337. (idx.call(arguments[0], window.location.host) > -1 ||
  1338. idx.call(arguments[0], '://') === -1))
  1339. window.addEventListener('unload', closeWindow, true);
  1340. _open.apply(window, arguments);
  1341. }.bind(window);
  1342.  
  1343. // Node.createElement wrapper to prevent click-dispatch in Google Chrome and similar browsers
  1344. let _createElement = Document.prototype.createElement;
  1345. Document.prototype.createElement = function createElement(name)
  1346. {
  1347. /*jshint validthis:true */
  1348. let el = _createElement.apply(this, arguments);
  1349. if (el.tagName === 'A')
  1350. el.addEventListener(
  1351. 'click', function(e)
  1352. {
  1353. if (!e.target.parentNode || !e.isTrusted)
  1354. window.addEventListener('unload', closeWindow, true);
  1355. }, false
  1356. );
  1357. return el;
  1358. };
  1359. console.log("Background redirect prevention enabled.");
  1360. }
  1361.  
  1362. // land wrapper on the page
  1363. let script = document.createElement('script');
  1364. script.textContent = '('+pbrLander.toString().replace(/%key%/g,key)+')();';
  1365. _appendChild(script);
  1366. _removeChild(script);
  1367. }
  1368.  
  1369. // Function to catch and block various methods to open a new window with 3rd-party content.
  1370. // Some advertisement networks went way past simple window.open call to circumvent default popup protection.
  1371. // This funciton blocks window.open, ability to restore original window.open from an IFRAME object,
  1372. // ability to perform an untrusted (not initiated by user) click on a link, click on a link without a parent
  1373. // node or simply a link with piece of javascript code in the HREF attribute.
  1374. function preventPopups()
  1375. {
  1376. if (inIFrame)
  1377. {
  1378. let i = -1, val;
  1379. do {
  1380. i++;
  1381. val = GM_getValue('forbid.popups.' + i);
  1382. } while(val & val !== win.location.href);
  1383. GM_setValue('forbid.popups.' + i, win.location.href);
  1384. win.top.postMessage('forbid.popups.' + i, '*');
  1385. return;
  1386. }
  1387.  
  1388. scriptLander(
  1389. function()
  1390. {
  1391. let _createElement = Document.prototype.createElement,
  1392. _appendChild = Element.prototype.appendChild;
  1393.  
  1394. function open()
  1395. {
  1396. '[native code]';
  1397. console.log('Site attempted to open a new window', arguments);
  1398. return {
  1399. document: {
  1400. write: () => {},
  1401. writeln: () => {}
  1402. }
  1403. };
  1404. }
  1405.  
  1406. function redefineOpen(obj)
  1407. {
  1408. Object.defineProperty(obj, 'open', {
  1409. get: () => open,
  1410. set: (val) => val,
  1411. enumerable: true
  1412. });
  1413. }
  1414. redefineOpen(win);
  1415.  
  1416. Document.prototype.createElement = function createElement(name)
  1417. {
  1418. /*jshint validthis:true */
  1419. let el = _createElement.apply(this, arguments);
  1420. if (el.tagName === 'A')
  1421. el.addEventListener(
  1422. 'click', function(e)
  1423. {
  1424. if (!e.target.parentNode || !e.isTrusted ||
  1425. (e.target.href && e.target.href.toLowerCase().indexOf('javascript') > -1))
  1426. {
  1427. e.preventDefault();
  1428. console.log('Blocked suspicious click event', e, 'on', e.target);
  1429. }
  1430. }, false
  1431. );
  1432. if (el.tagName === 'IFRAME')
  1433. el.addEventListener(
  1434. 'load', function(e)
  1435. {
  1436. try {
  1437. redefineOpen(e.target.contentWindow);
  1438. } catch(ignore) {}
  1439. }, false
  1440. );
  1441. return el;
  1442. };
  1443.  
  1444. Element.prototype.appendChild = function appendChild()
  1445. {
  1446. /*jshint validthis:true */
  1447. let el = _appendChild.apply(this, arguments);
  1448. if (el && el.nodeType === Node.ELEMENT_NODE && el.tagName === 'IFRAME') {
  1449. try {
  1450. redefineOpen(el.contentWindow);
  1451. } catch(ignore) {}
  1452. }
  1453. return el;
  1454. };
  1455. console.log('Popup prevention enabled.');
  1456. }
  1457. );
  1458. }
  1459. // External listener for case when site known to open popups were loaded in iframe
  1460. // It will sandbox any iframe which will send message 'forbid.popups' (preventPopups sends it)
  1461. // Some sites replace frame's window.location with data-url to run in clean context
  1462. if (!inIFrame)
  1463. {
  1464. let popWindows = new WeakSet();
  1465. window.addEventListener(
  1466. 'message', function(e)
  1467. {
  1468. if (typeof e.data === "string" && e.data.slice(0,13) === 'forbid.popups' &&
  1469. !popWindows.has(e.source))
  1470. {
  1471. let src = GM_getValue(e.data);
  1472. if (src)
  1473. GM_deleteValue(e.data);
  1474. popWindows.add(e.source); // remember window of iframe with suspected domain
  1475. for (let frame of document.querySelectorAll('iframe'))
  1476. if (frame.contentWindow === e.source)
  1477. {
  1478. if (frame.hasAttribute('sandbox'))
  1479. // remove allow-popups if frame already sandboxed
  1480. frame.sandbox.remove('allow-popups');
  1481. else
  1482. // set sandbox mode for troublesome frame and allow scripts and forms
  1483. frame.setAttribute('sandbox','allow-forms allow-scripts');
  1484. console.log('Disallowed popups from iframe', frame);
  1485.  
  1486. // reload frame content to apply restrictions
  1487. if (!src) {
  1488. src = frame.src;
  1489. console.log('Unable to get current iframe location, reloading from src', src);
  1490. } else
  1491. console.log('Reloading iframe with URL', src);
  1492. frame.src = 'about:blank';
  1493. frame.src = src;
  1494. }
  1495. }
  1496. }, false
  1497. );
  1498. }
  1499.  
  1500. // Currently unused piece of code developed to prevent site from registering serviceWorker
  1501. // and uninstall any existing instances of serivceWorker in case there is one already.
  1502. /* Commented out since not used
  1503. function forbidServiceWorker()
  1504. {
  1505. if (!("serviceWorker" in navigator))
  1506. return;
  1507. let svr = navigator.serviceWorker.ready;
  1508. Object.defineProperty(navigator, 'serviceWorker', {
  1509. value: {
  1510. register: function()
  1511. {
  1512. console.log('Registration of serviceWorker ' + arguments[0] + ' blocked.');
  1513. return new Promise(function(){});
  1514. },
  1515. ready: new Promise(() => null),
  1516. addEventListener: () => null
  1517. }
  1518. });
  1519. document.addEventListener(
  1520. 'DOMContentLoaded', function()
  1521. {
  1522. if (!svr)
  1523. return;
  1524. svr.then(
  1525. function(sw)
  1526. {
  1527. console.log('Found existing serviceWorker:', sw);
  1528. console.log('Attempting to unregister...');
  1529. sw.unregister().then(
  1530. () => console.log('Done.')
  1531. ).catch(
  1532. function(err)
  1533. {
  1534. console.log('Unregistration failed. :(', err);
  1535. console.log('Try to remove it manually:');
  1536. console.log(' 1. Open: chrome://serviceworker-internals/ (Google Chrome and alike) or about:serviceworkers (Mozilla Firefox) in a new tab.');
  1537. console.log(' 2. Search there for one with "'+document.domain+'" in the name.');
  1538. console.log(' 3. Use buttons in the same block with service you found to stop it and uninstall/unregister.');
  1539. }
  1540. );
  1541. }
  1542. ).catch(
  1543. (e) => console.log("LOL, existing serviceWorker failed on it's own! -_-", e)
  1544. );
  1545. }, false
  1546. );
  1547. }
  1548. /**/
  1549.  
  1550. // Currently obsolete code developed to prevent error and load calls on objects supposed to load resources
  1551. // from the internet like IMG or IFRAME, but missing SRC/HREF attribute. Usually tricks like this are used
  1552. // to unwrap wrapped functions to be able to load ads.
  1553. /* Commented out since not used
  1554. function errorAndLoadEventsFilter()
  1555. {
  1556. let toString = Function.prototype.toString,
  1557. _addEventListener = Element.prototype.addEventListener,
  1558. _removeEventListener = Element.prototype.removeEventListener,
  1559. hasAttribute = Element.prototype.hasAttribute,
  1560. evtMap = new WeakMap();
  1561. Element.prototype.addEventListener = function addEventListener(evt, func, capt) {
  1562. if ((evt === 'error' || evt === 'load') && !evtMap.get(func))
  1563. {
  1564. evtMap.set(
  1565. func, function()
  1566. {
  1567. if (hasAttribute.call(this, 'src') ||
  1568. hasAttribute.call(this, 'href'))
  1569. func.apply(this, arguments);
  1570. else
  1571. console.log('Blocked', evt, 'handler', toString.call(func), 'on', this);
  1572. }
  1573. );
  1574. }
  1575. _addEventListener.call(this, evt, (evtMap.get(func) || func), capt);
  1576. };
  1577. Element.prototype.removeEventListener = function removeEventListener(evt, func, capt) {
  1578. _removeEventListener.call(this, evt, (evtMap.get(func) || func), capt);
  1579. };
  1580. Object.defineProperty(HTMLElement.prototype, 'onload', {
  1581. set: function(func)
  1582. {
  1583. if(evtMap.has(this)) {
  1584. if (evtMap.get(this).onload)
  1585. _removeEventListener.call(this, 'load', evtMap.get(this).onload, false);
  1586. evtMap.get(this).onload = func;
  1587. } else
  1588. evtMap.set(this, { onload: func });
  1589.  
  1590. if (func)
  1591. _addEventListener.call(this, 'load', func, false);
  1592.  
  1593. return func;
  1594. },
  1595. get: function()
  1596. {
  1597. return evtMap.has(this) ? evtMap.get(this).onload : null;
  1598. }
  1599. });
  1600. Object.defineProperty(HTMLElement.prototype, 'onerror', {
  1601. set: function(func)
  1602. {
  1603. if (evtMap.has(this))
  1604. evtMap.get(this).onerror = func;
  1605. else
  1606. evtMap.set(this, { onerror: func });
  1607.  
  1608. if (func)
  1609. console.log('Blocked error handler', toString.call(func), 'on', this);
  1610.  
  1611. return func;
  1612. },
  1613. get: function()
  1614. {
  1615. return evtMap.has(this) ? evtMap.get(this).onerror : null;
  1616. }
  1617. });
  1618. }
  1619. /**/
  1620.  
  1621. // === Scripts for specific domains ===
  1622.  
  1623. let scripts = {};
  1624. // prevent popups and redirects block
  1625. // Popups
  1626. scripts.preventPopups = {
  1627. other: [
  1628. 'biqle.ru',
  1629. 'chaturbate.com',
  1630. 'dfiles.ru',
  1631. 'hentaiz.org',
  1632. 'mirrorcreator.com',
  1633. 'online-multy.ru', 'openload.co',
  1634. 'radikal.ru',
  1635. 'seedoff.cc', 'seedoff.tv',
  1636. 'tapochek.net', 'thepiratebay.org', 'torseed.net',
  1637. 'unionpeer.com',
  1638. 'zippyshare.com'
  1639. ],
  1640. now: preventPopups
  1641. };
  1642. // Background redirects
  1643. scripts.preventBackgroundRedirect = {
  1644. other: [
  1645. 'mediafire.com', 'megapeer.org', 'megapeer.ru',
  1646. 'perfectgirls.net',
  1647. 'turbobit.net'
  1648. ],
  1649. now: preventBackgroundRedirect
  1650. };
  1651.  
  1652. // other
  1653. scripts['4pda.ru'] = {
  1654. now: function()
  1655. {
  1656. // https://greasyfork.org/en/scripts/14470-4pda-unbrender
  1657. let hStyle,
  1658. isForum = document.location.href.search('/forum/') !== -1,
  1659. remove = (node) => (node ? node.parentNode.removeChild(node) : null),
  1660. afterClean = () => remove(hStyle);
  1661.  
  1662. function beforeClean()
  1663. {
  1664. // attach styles before document displayed
  1665. hStyle = createStyle([
  1666. 'html { overflow-y: scroll }',
  1667. 'section[id] {'+(
  1668. 'position: absolute;'+
  1669. 'width: 100%'
  1670. )+'}',
  1671. 'article + aside * { display: none !important }',
  1672. '#header + div:after {'+(
  1673. 'content: "";'+
  1674. 'position: fixed;'+
  1675. 'top: 0;'+
  1676. 'left: 0;'+
  1677. 'width: 100%;'+
  1678. 'height: 100%;'+
  1679. 'background-color: #E6E7E9'
  1680. )+'}',
  1681. // http://codepen.io/Beaugust/pen/DByiE
  1682. '@keyframes spin { 100% { transform: rotate(360deg) } }',
  1683. 'article + aside:after {'+(
  1684. 'content: "";'+
  1685. 'position: absolute;'+
  1686. 'width: 150px;'+
  1687. 'height: 150px;'+
  1688. 'top: 150px;'+
  1689. 'left: 50%;'+
  1690. 'margin-top: -75px;'+
  1691. 'margin-left: -75px;'+
  1692. 'box-sizing: border-box;'+
  1693. 'border-radius: 100%;'+
  1694. 'border: 10px solid rgba(0, 0, 0, 0.2);'+
  1695. 'border-top-color: rgba(0, 0, 0, 0.6);'+
  1696. 'animation: spin 2s infinite linear'
  1697. )+'}'
  1698. ], {id:'ubrHider'}, true);
  1699.  
  1700. // display content of a page if time to load a page is more than 2 seconds to avoid
  1701. // blocking access to a page if it is loading for too long or stuck in a loading state
  1702. setTimeout(2000, afterClean);
  1703. }
  1704.  
  1705. createStyle([
  1706. '#nav .use-ad { display: block !important }',
  1707. 'article:not(.post) + article:not(#id),'+
  1708. 'html:not(#id)>body:not(#id) a[target="_blank"] img[height="90"] { display: none !important }'
  1709. ]);
  1710.  
  1711. if (!isForum)
  1712. beforeClean();
  1713.  
  1714. // save links to non-overridden functions to use later
  1715. let protectedElems;
  1716. // protect/hide changed attributes in case site attempt to restore them
  1717. function styleProtector(eventMode)
  1718. {
  1719. let _toLowerCase = String.prototype.toLowerCase,
  1720. isStyleText = (t) => (_toLowerCase.call(t) === 'style'),
  1721. protectedElems = new WeakMap();
  1722. function protoOverride(element, functionName, isStyleCheck, returnIfProtected)
  1723. {
  1724. let originalFunction = element.prototype[functionName];
  1725. element.prototype[functionName] = function wrapper()
  1726. {
  1727. if (protectedElems.has(this) && isStyleCheck(arguments[0]))
  1728. return returnIfProtected(this, arguments);
  1729. return originalFunction.apply(this, arguments);
  1730. };
  1731. }
  1732. protoOverride(Element, 'removeAttribute', isStyleText, () => undefined);
  1733. protoOverride(Element, 'hasAttribute', isStyleText, (_this) => protectedElems.get(_this) !== null);
  1734. protoOverride(Element, 'setAttribute', isStyleText, (_this, args) => protectedElems.set(_this, args[1]));
  1735. protoOverride(Element, 'getAttribute', isStyleText, (_this) => protectedElems.get(_this));
  1736. if (!eventMode)
  1737. return protectedElems;
  1738. else
  1739. {
  1740. let e = document.createEvent('Event');
  1741. e.initEvent('protoOverride', false, false);
  1742. window.protectedElems = protectedElems;
  1743. window.dispatchEvent(e);
  1744. }
  1745. }
  1746. if (!isFirefox)
  1747. protectedElems = styleProtector(false);
  1748. else
  1749. {
  1750. let script = document.createElement('script');
  1751. script.textContent = '(' + styleProtector.toString() + ')(true);';
  1752. window.addEventListener(
  1753. 'protoOverride', function protoOverrideCallback(e)
  1754. {
  1755. if (win.protectedElems) {
  1756. protectedElems = win.protectedElems;
  1757. delete win.protectedElems;
  1758. }
  1759. document.removeEventListener('protoOverride', protoOverrideCallback, true);
  1760. }, true
  1761. );
  1762. _appendChild(script);
  1763. _removeChild(script);
  1764. }
  1765.  
  1766. // clean a page
  1767. window.addEventListener(
  1768. 'DOMContentLoaded', function()
  1769. {
  1770. let width = () => window.innerWidth || _de.clientWidth || document.body.clientWidth || 0;
  1771. let height = () => window.innerHeight || _de.clientHeight || document.body.clientHeight || 0;
  1772.  
  1773. if (isForum)
  1774. {
  1775. let si = document.querySelector('#logostrip');
  1776. if (si)
  1777. remove(si.parentNode.nextSibling);
  1778. }
  1779.  
  1780. if (document.location.href.search('/forum/dl/') !== -1) {
  1781. document.body.setAttribute('style', (document.body.getAttribute('style')||'')+
  1782. ';background-color:black!important');
  1783. for (let itm of document.querySelectorAll('body>div'))
  1784. if (!itm.querySelector('.dw-fdwlink'))
  1785. remove(itm);
  1786. }
  1787.  
  1788. if (isForum) // Do not continue if it's a forum
  1789. return;
  1790.  
  1791. {
  1792. let si = document.querySelector('#header');
  1793. if (si)
  1794. {
  1795. let rem = si.previousSibling;
  1796. while (rem)
  1797. {
  1798. si = rem.previousSibling;
  1799. remove(rem);
  1800. rem = si;
  1801. }
  1802. }
  1803. }
  1804.  
  1805. for (let itm of document.querySelectorAll('#nav li[class]'))
  1806. if (itm && itm.querySelector('a[href^="/tag/"]'))
  1807. remove(itm);
  1808.  
  1809. let style, result,
  1810. fakeStyles = new WeakMap(),
  1811. styleProxy = {
  1812. get: function(target, prop)
  1813. {
  1814. let fakeStyle = fakeStyles.get(target);
  1815. return ((prop in fakeStyle) ? fakeStyle : target)[prop];
  1816. },
  1817. set: function(target, prop, value)
  1818. {
  1819. let fakeStyle = fakeStyles.get(target);
  1820. ((prop in fakeStyle) ? fakeStyle : target)[prop] = value;
  1821. return value;
  1822. }
  1823. };
  1824. for (let itm of document.querySelectorAll('DIV, A'))
  1825. {
  1826. if (itm.tagName ==='DIV' &&
  1827. itm.offsetWidth > 0.95 * width() &&
  1828. itm.offsetHeight > 0.85 * height())
  1829. {
  1830. style = window.getComputedStyle(itm, null);
  1831. result = [];
  1832.  
  1833. if (style.backgroundImage !== 'none')
  1834. result.push('background-image:none!important');
  1835.  
  1836. if (style.backgroundColor !== 'transparent' &&
  1837. style.backgroundColor !== 'rgba(0, 0, 0, 0)')
  1838. result.push('background-color:transparent!important');
  1839.  
  1840. if (result.length)
  1841. {
  1842. if (itm.getAttribute('style'))
  1843. result.unshift(itm.getAttribute('style'));
  1844.  
  1845. fakeStyles.set(itm.style, {
  1846. 'backgroundImage': itm.style.backgroundImage,
  1847. 'backgroundColor': itm.style.backgroundColor
  1848. });
  1849.  
  1850. try {
  1851. Object.defineProperty(itm, 'style', {
  1852. value: new Proxy(itm.style, styleProxy),
  1853. enumerable: true
  1854. });
  1855. } catch (e) {
  1856. console.log('Unable to protect style property.', e);
  1857. }
  1858.  
  1859. if (protectedElems)
  1860. protectedElems.set(itm, _getAttribute.call(itm, 'style'));
  1861.  
  1862. _setAttribute.call(itm, 'style', result.join(';'));
  1863. }
  1864. }
  1865. if (itm.tagName ==='A' &&
  1866. (itm.offsetWidth > 0.95 * width() ||
  1867. itm.offsetHeight > 0.85 * height()))
  1868. {
  1869. if (protectedElems)
  1870. protectedElems.set(itm, _getAttribute.call(itm, 'style'));
  1871.  
  1872. _setAttribute.call(itm, 'style', 'display:none!important');
  1873. }
  1874. }
  1875.  
  1876. for (let itm of document.querySelectorAll('ASIDE>DIV'))
  1877. if ( ((itm.querySelector('script, iframe, a[href*="/ad/www/"]') ||
  1878. itm.querySelector('img[src$=".gif"]:not([height="0"]), img[height="400"]')) &&
  1879. !itm.classList.contains('post') ) || !itm.childNodes.length )
  1880. remove(itm);
  1881.  
  1882. document.body.setAttribute('style', (document.body.getAttribute('style')||'')+';background-color:#E6E7E9!important');
  1883.  
  1884. // display content of the page
  1885. afterClean();
  1886. }
  1887. );
  1888. }
  1889. };
  1890.  
  1891. scripts['allmovie.pro'] = {
  1892. other: ['rufilmtv.org'],
  1893. dom: function()
  1894. {
  1895. // pretend to be Android to make site use different played for ads
  1896. if (isSafari)
  1897. return;
  1898. Object.defineProperty(navigator, 'userAgent', {
  1899. 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'; },
  1900. enumerable: true
  1901. });
  1902. }
  1903. };
  1904.  
  1905. scripts['anidub-online.ru'] = {
  1906. other: ['online.anidub.com'],
  1907. dom: function()
  1908. {
  1909. if (win.ogonekstart1)
  1910. win.ogonekstart1 = () => console.log("Fire in the hole!");
  1911. },
  1912. now: () => createStyle([
  1913. '.background {background: none!important;}',
  1914. '.background > script + div,'+
  1915. '.background > script ~ div:not([id]):not([class]) + div[id][class]'+
  1916. '{display:none!important}'
  1917. ])
  1918. };
  1919.  
  1920. scripts['drive2.ru'] = () => gardener('.c-block:not([data-metrika="recomm"]),.o-grid__item', />Реклама<\//i);
  1921.  
  1922. scripts['fishki.net'] = () => gardener('.drag_list > .drag_element, .list-view > .paddingtop15, .post-wrap', /543769|Новости\sпартнеров/);
  1923.  
  1924. scripts['gidonline.club'] = {
  1925. now: () => createStyle('.tray > div[style] {display: none!important}')
  1926. };
  1927.  
  1928. scripts['hdgo.cc'] = {
  1929. other: ['46.30.43.38', 'couber.be'],
  1930. now: () => (new MutationObserver(
  1931. function(ms)
  1932. {
  1933. let m, node;
  1934. for (m of ms) for (node of m.addedNodes)
  1935. if (node.tagName === 'SCRIPT' && _getAttribute.call(node, 'onerror') !== null)
  1936. node.removeAttribute('onerror');
  1937. }
  1938. )).observe(document, { childList:true, subtree: true })
  1939. };
  1940.  
  1941. scripts['gismeteo.ru'] = {
  1942. other: ['gismeteo.ua'],
  1943. dom: () => gardener('div > a[target^="_"]', /Яндекс\.Директ/i, { root: 'body', observe: true, parent: 'div[class*="frame"]'})
  1944. };
  1945.  
  1946. scripts['hdrezka.me'] = {
  1947. now: function()
  1948. {
  1949. Object.defineProperty(win, 'fuckAdBlock', {
  1950. value: { onDetected: () => console.log('Pretending to be an ABP detector.') },
  1951. enumerable: true
  1952. });
  1953. Object.defineProperty(win, 'ab', {
  1954. value: false,
  1955. enumerable: true
  1956. });
  1957. },
  1958. dom: () => gardener('div[id][onclick][onmouseup][onmousedown]', /onmouseout/i)
  1959. };
  1960.  
  1961. scripts['imageban.ru'] = {
  1962. now: preventBackgroundRedirect,
  1963. dom: () => win.addEventListener(
  1964. 'unload', function()
  1965. {
  1966. window.location.hash = 'x'+Math.random().toString(36).substr(2);
  1967. }, true
  1968. )
  1969. };
  1970.  
  1971. scripts['mail.ru'] = {
  1972. // Trick to prevent mail.ru from removing 3rd-party styles
  1973. now: () => scriptLander(
  1974. () => Object.defineProperty(Object.prototype, 'restoreVisibility', {
  1975. get: () => (() => null),
  1976. set: () => null
  1977. })
  1978. )
  1979. };
  1980.  
  1981. scripts['megogo.net'] = {
  1982. now: function()
  1983. {
  1984. Object.defineProperty(win, "adBlock", {
  1985. get: () => false,
  1986. set: () => null,
  1987. enumerable : true
  1988. });
  1989. Object.defineProperty(win, "showAdBlockMessage", {
  1990. get: () => (() => null),
  1991. set: () => null,
  1992. enumerable: true
  1993. });
  1994. }
  1995. };
  1996.  
  1997. scripts['naruto-base.su'] = () => gardener('div[id^="entryID"],.block', /href="http.*?target="_blank"/i);
  1998.  
  1999. scripts['overclockers.ru'] = {
  2000. now: function()
  2001. {
  2002. createStyle('.fixoldhtml {display:block!important}');
  2003. if (!isChrome && !isOpera)
  2004. return; // Looks like my code works only in Chrome-like browsers
  2005. let noContentYet = true;
  2006. function jWrap()
  2007. {
  2008. win.$ = new Proxy(
  2009. win.$, {
  2010. apply: function(_$, _this, args)
  2011. {
  2012. let _ret = _$.apply(_this, args);
  2013. if (_ret[0] === document.body)
  2014. _ret.html = () => console.log('Anti-adblock prevented.');
  2015. return _ret;
  2016. }
  2017. }
  2018. );
  2019. win.jQuery = win.$;
  2020. }
  2021. (function jReady()
  2022. {
  2023. if (!win.$ && noContentYet)
  2024. setTimeout(jReady, 0);
  2025. else
  2026. jWrap();
  2027. })();
  2028. document.addEventListener ('DOMContentLoaded', () => (noContentYet = false), false);
  2029. }
  2030. };
  2031. scripts['forums.overclockers.ru'] = {
  2032. now: function()
  2033. {
  2034. createStyle('.needblock {position: fixed; left: -10000px}');
  2035. Object.defineProperty(win, 'adblck', {
  2036. get: () => 'no',
  2037. set: () => null,
  2038. enumerable: true
  2039. });
  2040. }
  2041. };
  2042.  
  2043. scripts['pb.wtf'] = {
  2044. other: ['piratbit.org', 'piratbit.ru'],
  2045. dom: function()
  2046. {
  2047. createStyle('.reques,#result,tbody.row1:not([id]) {display: none !important}');
  2048. // image in the slider in the header
  2049. gardener('a[href^="/ex"],a[href$="=="]', /img/i, {root:'.release-navbar', observe:true, parent:'div'});
  2050. // ads in blocks on the page
  2051. gardener('a[href^="/topic/234257"]', /Как\sразместить/i, {siblings:-1, root:'#main_content', observe:true, parent:'span[style]'});
  2052. // line above topic content
  2053. gardener('.re_top1', /./, {root:'#main_content', parent:'.hidden-sm'});
  2054. }
  2055. };
  2056.  
  2057. scripts['pikabu.ru'] = () => gardener('.story', /story__sponsor|story__gag|profile\/ads"/i, {root: '.inner_wrap', observe: true});
  2058.  
  2059. scripts['qrz.ru'] = {
  2060. now: function()
  2061. {
  2062. Object.defineProperty(win, 'ab', {
  2063. get:()=>false,
  2064. set:()=>null
  2065. });
  2066. Object.defineProperty(win, 'tryMessage', {
  2067. get:()=>(()=>null),
  2068. set:()=>null
  2069. });
  2070. }
  2071. };
  2072.  
  2073. scripts['razlozhi.ru'] = {
  2074. now: function()
  2075. {
  2076. for (let func of ['createShadowRoot', 'attachShadow'])
  2077. if (func in Element.prototype)
  2078. Element.prototype[func] = function(){ return this.cloneNode(); };
  2079. }
  2080. };
  2081.  
  2082. scripts['rp5.ru'] = {
  2083. other: ['rp5.by', 'rp5.kz', 'rp5.ua'],
  2084. dom: function()
  2085. {
  2086. createStyle('#bannerBottom {display: none!important}');
  2087. let co = document.querySelector('#content');
  2088. if (!co)
  2089. return;
  2090. let nodes = co.parentNode.childNodes,
  2091. i = nodes.length;
  2092. while (i--)
  2093. if (nodes[i] !== co)
  2094. nodes[i].parentNode.removeChild(nodes[i]);
  2095. }
  2096. };
  2097.  
  2098. scripts['rustorka.com'] = {
  2099. other: ['rumedia.ws'],
  2100. now: function()
  2101. {
  2102. createStyle('.header > div:not(.head-block) a, #sidebar1 img, #logo img {opacity:0!important}', {
  2103. id: 'tempHidingStyles'
  2104. }, true);
  2105. preventPopups();
  2106. },
  2107. dom: function()
  2108. {
  2109. for (let o of document.querySelectorAll('IMG, A'))
  2110. if ((o.clientWidth === 728 && o.clientHeight === 90) ||
  2111. (o.clientWidth === 300 && o.clientHeight === 250))
  2112. {
  2113. while (o && o.tagName !== 'A')
  2114. o = o.parentNode;
  2115. if (o)
  2116. _setAttribute.call(o, 'style', 'display: none !important');
  2117. }
  2118. let s = document.querySelector('#tempHidingStyles');
  2119. s.parentNode.removeChild(s);
  2120. }
  2121. };
  2122.  
  2123. scripts['sport-express.ru'] = () => gardener('.js-relap__item',/>Реклама\s+<\//, {root:'.container', observe: true});
  2124.  
  2125. scripts['sports.ru'] = function()
  2126. {
  2127. gardener('.aside-news-list__item', /aside-news-list__advert/i, {root:'.columns-layout__left', observe: true});
  2128. gardener('.material-list__item', /Реклама/i, {root:'.columns-layout', observe: true});
  2129. // extra functionality: shows/hides panel at the top depending on scroll direction
  2130. createStyle([
  2131. '.user-panel__fixed { transition: top 0.2s ease-in-out!important; }',
  2132. '.user-panel-up { top: -40px!important }'
  2133. ], {id: 'userPanelSlide'}, false);
  2134. (function lookForPanel()
  2135. {
  2136. let panel = document.querySelector('.user-panel__fixed');
  2137. if (!panel)
  2138. setTimeout(lookForPanel, 100);
  2139. else
  2140. window.addEventListener(
  2141. 'wheel', function(e)
  2142. {
  2143. if (e.deltaY > 0 && !panel.classList.contains('user-panel-up'))
  2144. panel.classList.add('user-panel-up');
  2145. else if (e.deltaY < 0 && panel.classList.contains('user-panel-up'))
  2146. panel.classList.remove('user-panel-up');
  2147. }, false
  2148. );
  2149. })();
  2150. };
  2151.  
  2152. scripts['vk.com'] = () => gardener('div[data-post-id]', /wall_marked_as_ads/, {root: '#page_wall_posts', observe: true});
  2153.  
  2154. scripts['yap.ru'] = {
  2155. other: ['yaplakal.com'],
  2156. dom: function()
  2157. {
  2158. gardener('form > table[id^="p_row_"]:nth-of-type(2)', /member1438|Administration/);
  2159. gardener('.icon-comments', /member1438|Administration|\/go\/\?http/, {parent:'tr', siblings:-2});
  2160. }
  2161. };
  2162.  
  2163. scripts['rambler.ru'] = {
  2164. other: ['championat.com','gazeta.ru','lenta.ru'],
  2165. now: () => scriptLander(
  2166. function()
  2167. {
  2168. let _createElement = Document.prototype.createElement,
  2169. loadMap = new WeakMap();
  2170. Document.prototype.createElement = function createElement(name) {
  2171. /*jshint validthis:true */
  2172. let el = _createElement.apply(this, arguments);
  2173. if (el.tagName !== 'LINK')
  2174. return el;
  2175. Object.defineProperty(el, 'onload', {
  2176. get: function() {
  2177. return loadMap.get(loadMap.get(this));
  2178. },
  2179. set: function(func) {
  2180. let wrap = loadMap.get(this),
  2181. isContent = /\{\s*content\s*:\s*"[^"]+"/i;
  2182. if (wrap)
  2183. {
  2184. this.removeEventListener('load', wrap, false);
  2185. loadMap.remove(wrap);
  2186. loadMap.remove(this);
  2187. }
  2188. wrap = function(e)
  2189. {
  2190. if (e.target && e.target.sheet && e.target.sheet.cssRules &&
  2191. e.target.sheet.cssRules[0] && e.target.sheet.cssRules[0].cssText &&
  2192. isContent.test(e.target.sheet.cssRules[0].cssText))
  2193. {
  2194. console.log('Blocked "onload" for', e.target.href);
  2195. return false;
  2196. }
  2197. return func.apply(this, arguments);
  2198. };
  2199. loadMap.set(this, wrap);
  2200. loadMap.set(wrap, func);
  2201. this.addEventListener('load', wrap, false);
  2202. },
  2203. enumberable: true
  2204. });
  2205. return el;
  2206. };
  2207. }
  2208. )
  2209. };
  2210.  
  2211. scripts['reactor.cc'] = {
  2212. other: ['joyreactor.cc', 'pornreactor.cc'],
  2213. now: function()
  2214. {
  2215. win.open = (function(){ throw new Error('Redirect prevention.'); }).bind(window);
  2216. },
  2217. click: function(e)
  2218. {
  2219. let node = e.target;
  2220. if (node.nodeType === Node.ELEMENT_NODE &&
  2221. node.style.position === 'absolute' &&
  2222. node.style.zIndex > 0)
  2223. node.parentNode.removeChild(node);
  2224. },
  2225. dom: function()
  2226. {
  2227. let words = new RegExp(
  2228. 'блокировщика рекламы'
  2229. .split('')
  2230. .map(function(e){return e+'[\u200b\u200c\u200d]*';})
  2231. .join('')
  2232. .replace(' ', '\\s*')
  2233. .replace(/[аоре]/g, function(e){return ['[аa]','[оo]','[рp]','[еe]']['аоре'.indexOf(e)];}),
  2234. 'i'),
  2235. can;
  2236. function deeper(spider)
  2237. {
  2238. let c, l, n;
  2239. if (words.test(spider.innerText))
  2240. {
  2241. if (spider.nodeType === Node.TEXT_NODE)
  2242. return true;
  2243. c = spider.childNodes;
  2244. l = c.length;
  2245. n = 0;
  2246. while(l--)
  2247. if (deeper(c[l]), can)
  2248. n++;
  2249. if (n > 0 && n === c.length && spider.offsetHeight < 750)
  2250. can.push(spider);
  2251. return false;
  2252. }
  2253. return true;
  2254. }
  2255. function probe()
  2256. {
  2257. if (words.test(document.body.innerText))
  2258. {
  2259. can = [];
  2260. deeper(document.body);
  2261. let i = can.length, spider;
  2262. while(i--) {
  2263. spider = can[i];
  2264. if (spider.offsetHeight > 10 && spider.offsetHeight < 750)
  2265. _setAttribute.call(spider, 'style', 'background:none!important');
  2266. }
  2267. }
  2268. }
  2269. (new MutationObserver(probe))
  2270. .observe(document, { childList:true, subtree:true });
  2271. }
  2272. };
  2273.  
  2274. scripts['auto.ru'] = function()
  2275. {
  2276. let words = /Реклама|Яндекс.Директ|yandex_ad_/;
  2277. let userAdsListAds = (
  2278. '.listing-list > .listing-item,'+
  2279. '.listing-item_type_fixed.listing-item'
  2280. );
  2281. let catalogAds = (
  2282. 'div[class*="layout_catalog-inline"],'+
  2283. 'div[class$="layout_horizontal"]'
  2284. );
  2285. let otherAds = (
  2286. '.advt_auto,'+
  2287. '.sidebar-block,'+
  2288. '.pager-listing + div[class],'+
  2289. '.card > div[class][style],'+
  2290. '.sidebar > div[class],'+
  2291. '.main-page__section + div[class],'+
  2292. '.listing > tbody'
  2293. );
  2294. gardener(userAdsListAds, words, {root:'.listing-wrap', observe:true});
  2295. gardener(catalogAds, words, {root:'.catalog__page,.content__wrapper', observe:true});
  2296. gardener(otherAds, words);
  2297. };
  2298.  
  2299. scripts['rsload.net'] = {
  2300. load: function()
  2301. {
  2302. let dis = document.querySelector('label[class*="cb-disable"]');
  2303. if (dis)
  2304. dis.click();
  2305. },
  2306. click: function(e)
  2307. {
  2308. let t = e.target;
  2309. if (t && t.href && (/:\/\/\d+\.\d+\.\d+\.\d+\//.test(t.href)))
  2310. t.href = t.href.replace('://','://rsload.net:rsload.net@');
  2311. }
  2312. };
  2313.  
  2314. let domain, name;
  2315. // add alternate domain names if present
  2316. for (name in scripts) if (scripts[name].other)
  2317. for (domain of scripts[name].other) if (!(domain in scripts))
  2318. scripts[domain] = scripts[name];
  2319. // look for current domain in the list and run appropriate code
  2320. domain = document.domain;
  2321. while (domain.indexOf('.') > -1)
  2322. {
  2323. if (domain in scripts)
  2324. {
  2325. if (typeof scripts[domain] === 'function')
  2326. {
  2327. document.addEventListener ('DOMContentLoaded', scripts[domain], false);
  2328. break;
  2329. }
  2330. for (name in scripts[domain])
  2331. switch(name)
  2332. {
  2333. case 'other':
  2334. break;
  2335. case 'now':
  2336. scripts[domain][name]();
  2337. break;
  2338. case 'load':
  2339. window.addEventListener('load', scripts[domain][name], false);
  2340. break;
  2341. case 'dom':
  2342. document.addEventListener('DOMContentLoaded', scripts[domain][name], false);
  2343. break;
  2344. default:
  2345. document.addEventListener (name, scripts[domain][name], false);
  2346. }
  2347. }
  2348. domain = domain.slice(domain.indexOf('.') + 1);
  2349. }
  2350. })();