RU AdList JS Fixes

try to take over the world!

目前为 2017-09-28 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name RU AdList JS Fixes
  3. // @namespace ruadlist_js_fixes
  4. // @version 20170927.4
  5. // @description try to take over the world!
  6. // @author lainverse & dimisa
  7. // @match *://*/*
  8. // @grant unsafeWindow
  9. // @grant window.close
  10. // @grant GM_getValue
  11. // @grant GM_setValue
  12. // @run-at document-start
  13. // ==/UserScript==
  14.  
  15. (function() {
  16. 'use strict';
  17. let win = (unsafeWindow || window),
  18. // http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
  19. isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0,
  20. isChrome = !!window.chrome && !!window.chrome.webstore,
  21. isSafari = (Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0 ||
  22. (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window.safari || safari.pushNotification)),
  23. isFirefox = typeof InstallTrigger !== 'undefined',
  24. inIFrame = (win.self !== win.top),
  25. _getAttribute = Element.prototype.getAttribute,
  26. _setAttribute = Element.prototype.setAttribute,
  27. _de = document.documentElement,
  28. _appendChild = Document.prototype.appendChild.bind(_de),
  29. _removeChild = Document.prototype.removeChild.bind(_de),
  30. _createElement = Document.prototype.createElement.bind(document);
  31.  
  32. if (isFirefox && // Exit on image pages in Fx
  33. document.constructor.prototype.toString() === '[object ImageDocumentPrototype]')
  34. return;
  35.  
  36. // dTree 2.05 in some cases replaces Node object before my script kicks in :(
  37. if (!Node.prototype)
  38. {
  39. let ifr = _createElement('iframe');
  40. _appendChild(ifr);
  41. try {
  42. window.Node = ifr.contentWindow.Node;
  43. console.log('Node object restored. -_-');
  44. } catch(e) {
  45. console.log('Unable to restore Node object.', e);
  46. }
  47. _removeChild(ifr);
  48. }
  49.  
  50. // NodeList iterator polyfill (mostly for Safari)
  51. // https://jakearchibald.com/2014/iterators-gonna-iterate/
  52. if (!NodeList.prototype[Symbol.iterator]) {
  53. NodeList.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
  54. }
  55.  
  56. // Options
  57. let opts = {
  58. 'useWSIFunc': useWSI
  59. };
  60.  
  61. {
  62. let optsCall = function(callback)
  63. {
  64. // Register event listener
  65. let key = "optsCallEvent_" + Math.random().toString(36).substr(2),
  66. cb = callback.func.bind(callback.name);
  67. window.addEventListener(key, cb, false);
  68. // Generate and dispatch synthetic event
  69. let ev = document.createEvent("HTMLEvents");
  70. ev.initEvent(key, true, false);
  71. window.dispatchEvent(ev);
  72. // Remove listener
  73. window.removeEventListener(key, cb, false);
  74. };
  75.  
  76. let initOptsHandler = function()
  77. {
  78. opts[this] = GM_getValue(this, true);
  79. if (opts[this])
  80. opts[this+'Func']();
  81. };
  82.  
  83. optsCall({
  84. func: initOptsHandler,
  85. name: 'useWSI'
  86. });
  87.  
  88. // show options page
  89. let openOptions = function()
  90. {
  91. let ovl = _createElement('div'),
  92. inner = _createElement('div');
  93. ovl.style = (
  94. 'position: fixed;'+
  95. 'top:0; left:0;'+
  96. 'bottom: 0; right: 0;'+
  97. 'background: rgba(0,0,0,0.85);'+
  98. 'z-index: 2147483647;'+
  99. 'padding: 5em'
  100. );
  101. inner.style = (
  102. 'background: whitesmoke;'+
  103. 'font-size: 10pt;'+
  104. 'color: black;'+
  105. 'padding: 1em'
  106. );
  107. inner.textContent = 'JS Fixes Options: (reload page to apply)';
  108. inner.appendChild(_createElement('br'));
  109. inner.appendChild(_createElement('br'));
  110. ovl.addEventListener(
  111. 'click', function(e)
  112. {
  113. if (e.target === ovl) {
  114. ovl.parentNode.removeChild(ovl);
  115. e.preventDefault();
  116. }
  117. e.stopPropagation();
  118. }, false
  119. );
  120. // append checkbox with label function
  121. function addCheckbox(optName, optLabel)
  122. {
  123. let c = _createElement('input'),
  124. l = _createElement('label');
  125. c.type = 'checkbox';
  126. c.id = optName;
  127. optsCall({
  128. func: function()
  129. {
  130. c.checked = GM_getValue(this);
  131. },
  132. name: optName
  133. });
  134. c.addEventListener(
  135. 'click', function(e)
  136. {
  137. optsCall({
  138. func:function(){
  139. GM_setValue(this, e.target.checked);
  140. opts[this] = e.target.checked;
  141. },
  142. name:optName
  143. });
  144. }, true
  145. );
  146. l.textContent = optLabel;
  147. l.setAttribute('for', optName);
  148. inner.appendChild(c);
  149. inner.appendChild(l);
  150. inner.appendChild(_createElement('br'));
  151. }
  152. // append checkboxes
  153. addCheckbox('useWSI', 'Use WebSocket filter. Disable if experience problems with WebSocket connections.');
  154. document.body.appendChild(ovl);
  155. ovl.appendChild(inner);
  156. };
  157.  
  158. // monitor keys pressed for Ctrl+Alt+Shift+J > s > f code
  159. let opPos = 0, opKey = ['KeyJ','KeyS','KeyF'];
  160. document.addEventListener(
  161. 'keydown', function(e)
  162. {
  163. if ((e.code === opKey[opPos] || e.location) &&
  164. (!!opPos || e.altKey && e.ctrlKey && e.shiftKey))
  165. {
  166. opPos += e.location ? 0 : 1;
  167. e.stopPropagation();
  168. e.preventDefault();
  169. } else {
  170. opPos = 0;
  171. }
  172. if (opPos === opKey.length)
  173. {
  174. opPos = 0;
  175. openOptions();
  176. }
  177. }, false
  178. );
  179. }
  180.  
  181. // Special wrapper script to run scripts designed to override standard DOM functions
  182. // In Firefox appends supplied script to a page to make it run in page context and let
  183. // page content access overridden functions. In other browsers just run it as-is.
  184. function scriptLander(func, prepend)
  185. {
  186. if (!isFirefox)
  187. {
  188. func();
  189. return;
  190. }
  191. let script = _createElement('script');
  192. let inline = ['string', 'function'];
  193. script.textContent = '!function(){let win=window;' + (
  194. inline.includes(typeof prepend) && prepend ||
  195. prepend instanceof Array && prepend.join(';') || ''
  196. ) + ';(' + func + ')();}();';
  197. _appendChild(script);
  198. _removeChild(script);
  199. }
  200.  
  201. function nullTools(log) {
  202. // jshint validthis:true
  203. let nt = this;
  204. function trace() { if (log) console.trace.apply(this, arguments); }
  205.  
  206. nt.define = function(obj, prop, val)
  207. {
  208. Object.defineProperty(
  209. obj, prop, {
  210. get: () => (trace('get', prop, 'of', obj, 'which is', val), val),
  211. set: (v) => (trace('set', prop, 'of', obj, 'to', v), undefined),
  212. enumerable: true
  213. }
  214. );
  215. };
  216. nt.proxy = function(obj)
  217. {
  218. return new Proxy(
  219. obj, {
  220. get: (t, p) => (trace('get', p, 'of', t, 'which is', t[p]), t[p]),
  221. set: (t, p, v) => (trace('set', p, 'of', t, 'to', v), true)
  222. }
  223. );
  224. };
  225. nt.func = (val) => () => (trace('call func, return', val), val);
  226. }
  227.  
  228. // Fake objects of advertisement networks to break their workflow
  229. scriptLander(
  230. function()
  231. {
  232. let nt = new nullTools();
  233. // Popular adblock detector
  234. if (!('fuckAdBlock' in win))
  235. {
  236. let FuckAdBlock = function(options) {
  237. let self = this;
  238. self._options = {
  239. checkOnLoad: false,
  240. resetOnEnd: false,
  241. checking: false
  242. };
  243. self.setOption = function(opt, val)
  244. {
  245. if (val)
  246. self._options[opt] = val;
  247. else
  248. Object.assign(self._options, opt);
  249. };
  250. if (options)
  251. self.setOption(options);
  252.  
  253. self._var = { event: {} };
  254. self.clearEvent = function()
  255. {
  256. self._var.event.detected = [];
  257. self._var.event.notDetected = [];
  258. };
  259. self.clearEvent();
  260.  
  261. self.on = function(detected, fun)
  262. {
  263. self._var.event[detected?'detected':'notDetected'].push(fun);
  264. return self;
  265. };
  266. self.onDetected = function(cb)
  267. {
  268. return self.on(true, cb);
  269. };
  270. self.onNotDetected = function(cb)
  271. {
  272. return self.on(false, cb);
  273. };
  274. self.emitEvent = function()
  275. {
  276. for (let fun of self._var.event.notDetected)
  277. fun();
  278. if (self._options.resetOnEnd)
  279. self.clearEvent();
  280. return self;
  281. };
  282. self._creatBait = () => null;
  283. self._destroyBait = () => null;
  284. self._checkBait = function() {
  285. setTimeout((() => self.emitEvent()), 1);
  286. };
  287. self.check = function() {
  288. self._checkBait();
  289. return true;
  290. };
  291.  
  292. let callback = function()
  293. {
  294. if (self._options.checkOnLoad)
  295. setTimeout(self.check, 1);
  296. };
  297. window.addEventListener('load', callback, false);
  298. };
  299. nt.define(win, 'FuckAdBlock', FuckAdBlock);
  300. nt.define(win, 'fuckAdBlock', new FuckAdBlock({
  301. checkOnLoad: true,
  302. resetOnEnd: true
  303. }));
  304. }
  305.  
  306. // CoinHive miner stub. Continuous 100% CPU load can easily kill some CPU with overheat.
  307. let CoinHive = nt.proxy({
  308. Anonymous: function()
  309. {
  310. return {
  311. setThrottle: nt.func(null),
  312. start: nt.func(null)
  313. };
  314. },
  315. User: function() {
  316. return this.Anonymous();
  317. },
  318. JobThread: nt.func(null),
  319. Token: nt.func(null)
  320. });
  321. if (!('CoinHive' in win))
  322. nt.define(win, 'CoinHive', CoinHive);
  323.  
  324. // Yandex API (ADBTools, Metrika)
  325. let hostname = location.hostname;
  326. if (hostname.startsWith('google.') || hostname.includes('.google.') ||
  327. // Google likes to define odd global variables like Ya
  328. ((hostname.startsWith('yandex.') || hostname.includes('.yandex.')) &&
  329. /^\/((yand)?search|images)/i.test(location.pathname) &&
  330. !hostname.startsWith('news.')) ||
  331. // Also, Yandex uses their Ya object for a lot of things on their pages and
  332. // wrapping it may cause problems. It's better to skip it in some cases.
  333. hostname.endsWith('github.io') || hostname.endsWith('grimtools.com'))
  334. return;
  335.  
  336. let Ya = new Proxy({}, {
  337. set: function(tgt, prop, val)
  338. {
  339. if (val && typeof val === 'object' && 'AdvManager' in val)
  340. val = tgt.Context;
  341. tgt[prop] = val;
  342. return true;
  343. },
  344. get: (tgt, prop) => tgt[prop]
  345. });
  346. let callWithParams = function(f)
  347. {
  348. f.call(this, Ya.__inline_params__ || {});
  349. Ya.__inline_params__ = null;
  350. };
  351. nt.define(Ya, 'callWithParams', callWithParams);
  352. nt.define(Ya, 'PerfCounters', nt.proxy({
  353. addCacheEvent: nt.func(null),
  354. getTime: nt.func(null),
  355. sendCacheEvents: nt.func(null),
  356. sendResTiming: nt.func(null),
  357. sendTimeMark: nt.func(null),
  358. __cacheEvents: []
  359. }));
  360. nt.define(Ya, '__isSent', true);
  361. let extra = nt.proxy({
  362. extra: nt.proxy({ match: 0, confirm: '', src: '' }),
  363. id: 0, percent: 100, threshold: 1
  364. });
  365. nt.define(Ya, '_exp', nt.proxy({
  366. id: 0, coin: 0,
  367. choose: nt.func(extra),
  368. get: (prop) => extra.hasOwnProperty(prop) ? extra[prop] : null,
  369. getId: nt.func(0),
  370. defaultVersion: extra,
  371. getExtra: nt.func(extra.extra),
  372. getDefaultExtra: nt.func(extra.extra),
  373. versions: [extra]
  374. }));
  375. nt.define(Ya, 'c', nt.func(null));
  376. nt.define(Ya, 'ADBTools', function(){
  377. for (let name of ['loadContext', 'testAdbStyle'])
  378. this[name] = nt.func(null);
  379. this.getCurrentState = nt.func(true);
  380. return nt.proxy(this);
  381. });
  382. if (!location.hostname.includes('kinopoisk.ru'))
  383. // kinopoisk uses adfox wrapped in Yandex code to display self-ads
  384. nt.define(Ya, 'adfoxCode', nt.proxy({
  385. create: nt.func(null),
  386. createAdaptive: nt.func(null),
  387. createScroll: nt.func(null)
  388. }));
  389. let AdvManager = function()
  390. {
  391. for (let name of ['renderDirect', 'getBid', 'releaseBid', 'getSkipToken', 'getAdSessionId'])
  392. this[name] = nt.func(null);
  393. this.render = function(o) {
  394. if (!o.renderTo)
  395. return;
  396. let placeholder = document.getElementById(o.renderTo);
  397. let parent = placeholder.parentNode;
  398. placeholder.style = 'display:none!important';
  399. parent.style = (parent.getAttribute('style')||'') + 'height:auto!important';
  400. // fix for Yandex TV pages
  401. if (location.hostname.startsWith('tv.yandex.'))
  402. {
  403. let sibling = placeholder.previousSibling;
  404. if (sibling && sibling.classList && sibling.classList.contains('tv-spin'))
  405. sibling.style.display = 'none';
  406. }
  407. };
  408. return nt.proxy(this);
  409. };
  410. nt.define(Ya, 'Context', nt.proxy({
  411. _callbacks: nt.proxy([]),
  412. _asyncModeOn: true,
  413. _init: nt.func(null),
  414. AdvManager: new AdvManager()
  415. }));
  416. let Metrika = function()
  417. {
  418. for (let name of ['reachGoal', 'replacePhones', 'trackLinks', 'hit', 'params'])
  419. this[name] = nt.func(null);
  420. this.id = 0;
  421. return nt.proxy(this);
  422. };
  423. Metrika.counters = () => Ya._metrika.counters;
  424. nt.define(Ya, 'Metrika', Metrika);
  425. let counter = new Ya.Metrika();
  426. nt.define(Ya, '_metrika', nt.proxy({
  427. counter: counter,
  428. counters: [counter],
  429. hitParam: {},
  430. counterNum: 0,
  431. hitId: 0,
  432. v: 1
  433. }));
  434. nt.define(Ya, '_globalMetrikaHitId', 0);
  435. nt.define(win, 'Ya', Ya);
  436. // Yandex.Metrika callbacks
  437. let yandex_metrika_callbacks = [];
  438. document.addEventListener(
  439. 'DOMContentLoaded',
  440. (e) => {
  441. yandex_metrika_callbacks.forEach((f) => f && f.call(window));
  442. yandex_metrika_callbacks.length = 0;
  443. yandex_metrika_callbacks.push = (f) => setTimeout(f, 0);
  444. },
  445. false
  446. );
  447. nt.define(win, 'yandex_metrika_callbacks', yandex_metrika_callbacks);
  448. }, nullTools
  449. );
  450.  
  451. // Creates and return protected style (unless protection is manually disabled).
  452. // Protected style will re-add itself on removal and remaind enabled on attempt to disable it.
  453. function createStyle(rules, props, skip_protect)
  454. {
  455. props = props || {};
  456. props.type = 'text/css';
  457.  
  458. function _protect(style)
  459. {
  460. if (skip_protect)
  461. return;
  462.  
  463. Object.defineProperty(style, 'sheet', {
  464. value: null,
  465. enumerable: true
  466. });
  467. Object.defineProperty(style, 'disabled', {
  468. get: () => true, //pretend to be disabled
  469. set: () => undefined,
  470. enumerable: true
  471. });
  472. (new MutationObserver(
  473. (ms) => _removeChild(ms[0].target)
  474. )).observe(style, { childList: true });
  475. }
  476.  
  477.  
  478. function _create()
  479. {
  480. let style = _appendChild(_createElement('style'));
  481. Object.assign(style, props);
  482.  
  483. function insertRules(rule)
  484. {
  485. if (rule.forEach)
  486. rule.forEach(insertRules);
  487. else try {
  488. style.sheet.insertRule(rule, 0);
  489. } catch (e) {
  490. console.error(e);
  491. }
  492. }
  493.  
  494. insertRules(rules);
  495. _protect(style);
  496.  
  497. return style;
  498. }
  499.  
  500. let style = _create();
  501. if (skip_protect)
  502. return style;
  503.  
  504. function resolveInANewContext(resolve)
  505. {
  506. setTimeout(
  507. (resolve) => resolve(_create()),
  508. 0, resolve
  509. );
  510. }
  511.  
  512. (new MutationObserver(
  513. function(ms)
  514. {
  515. let m, node;
  516. for (m of ms) for (node of m.removedNodes)
  517. if (node === style)
  518. (new Promise(resolveInANewContext))
  519. .then((st) => (style = st));
  520. }
  521. )).observe(_de, { childList: true });
  522.  
  523. return style;
  524. }
  525.  
  526. // https://greasyfork.org/scripts/19144-websuckit/
  527. function useWSI()
  528. {
  529. // check does browser support Proxy and WebSocket
  530. if (typeof Proxy !== 'function' ||
  531. typeof WebSocket !== 'function')
  532. return;
  533.  
  534. function getWrappedCode(removeSelf)
  535. {
  536. let text = getWrappedCode.toString() + WSI.toString();
  537. text = (
  538. '(function(){"use strict";'+
  539. text.replace(/\/\/[^\r\n]*/g,'').replace(/[\s\r\n]+/g,' ')+
  540. '(new WSI(self||window)).init();'+
  541. (removeSelf?'let s = document.currentScript; if (s) {s.parentNode.removeChild(s);}':'')+
  542. '})();\n'
  543. );
  544. return text;
  545. }
  546.  
  547. function WSI(win, safeWin)
  548. {
  549. safeWin = safeWin || win;
  550. let masks = [], filter;
  551. for (filter of [// blacklist
  552. '||185.87.50.147^',
  553. '||10root25.website^', '||24video.xxx^',
  554. '||adlabs.ru^', '||adspayformymortgage.win^', '||aviabay.ru^',
  555. '||bgrndi.com^', '||brokeloy.com^',
  556. '||cnamerutor.ru^',
  557. '||docfilms.info^', '||dreadfula.ru^',
  558. '||et-code.ru^', '||etcodes.com^',
  559. '||franecki.net^', '||film-doma.ru^',
  560. '||free-torrent.org^', '||free-torrent.pw^',
  561. '||free-torrents.org^', '||free-torrents.pw^',
  562. '||game-torrent.info^', '||gocdn.ru^',
  563. '||hdkinoshka.com^', '||hghit.com^', '||hindcine.net^',
  564. '||kiev.ua^', '||kinotochka.net^',
  565. '||kinott.com^', '||kinott.ru^', '||kuveres.com^',
  566. '||lepubs.com^', '||luxadv.com^', '||luxup.ru^', '||luxupcdna.com^',
  567. '||mail.ru^', '||marketgid.com^', '||mixadvert.com^', '||mxtads.com^',
  568. '||nickhel.com^',
  569. '||oconner.biz^', '||oconner.link^', '||octoclick.net^', '||octozoon.org^',
  570. '||pkpojhc.com^',
  571. '||psma01.com^', '||psma02.com^', '||psma03.com^',
  572. '||recreativ.ru^', '||redtram.com^', '||regpole.com^', '||rootmedia.ws^', '||ruttwind.com^',
  573. '||skidl.ru^',
  574. '||torvind.com^', '||traffic-media.co^', '||trafmag.com^',
  575. '||webadvert-gid.ru^', '||webadvertgid.ru^',
  576. '||xxuhter.ru^',
  577. '||yuiout.online^',
  578. '||zoom-film.ru^'])
  579. masks.push(new RegExp(
  580. filter.replace(/([\\\/\[\].*+?(){}$])/g, '\\$1')
  581. .replace(/\^(?!$)/g,'\\.?[^\\w%._-]')
  582. .replace(/\^$/,'\\.?([^\\w%._-]|$)')
  583. .replace(/^\|\|/,'^(ws|http)s?:\\/+([^\/.]+\\.)*'),
  584. 'i'));
  585.  
  586. function isBlocked(url) {
  587. for (let mask of masks)
  588. if (mask.test(url))
  589. return true;
  590. return false;
  591. }
  592.  
  593. function wrapWebSocket(wsParent)
  594. {
  595. let _WebSocket = wsParent.WebSocket;
  596. // getter for properties of fake WS, returns fake functions
  597. // if there are functions with such name in the real WS and
  598. // also returns constants from real WS
  599. function wsGetter(target, name)
  600. {
  601. try {
  602. if (typeof _WebSocket.prototype[name] === 'function')
  603. {
  604. if (name === 'close' || name === 'send') // send also closes connection
  605. target.readyState = _WebSocket.CLOSED;
  606. return (
  607. function fake() {
  608. console.trace(`[WSI] Invoked function "${name}'"`);
  609. return;
  610. }
  611. );
  612. }
  613. if (typeof _WebSocket.prototype[name] === 'number')
  614. return _WebSocket[name];
  615. } catch(ignore) {}
  616. return target[name];
  617. }
  618. // Wrap WS object
  619. wsParent.WebSocket = new Proxy(_WebSocket, {
  620. construct: function (target, args)
  621. {
  622. let url = args[0];
  623. console.log(`[WSI] Opening socket on ${url}\u2026`);
  624. if (isBlocked(url))
  625. {
  626. console.log("[WSI] Blocked.");
  627. return new Proxy({
  628. url: url,
  629. readyState: _WebSocket.OPEN
  630. }, {
  631. get: wsGetter,
  632. set: () => true
  633. });
  634. }
  635. return Reflect.construct(target, args);
  636. }
  637. });
  638. }
  639.  
  640. function WorkerWrapper()
  641. {
  642. let realWorker = win.Worker;
  643. win.Worker = function Worker() {
  644. let isBlobURL = /^blob:/i,
  645. resourceURI = arguments[0],
  646. deepLogMode = false,
  647. _callbacks = new WeakMap(),
  648. _worker = null,
  649. _onevs = { names: ['onmessage', 'onerror'] },
  650. _actions = [],
  651. _self = this;
  652.  
  653. function log()
  654. {
  655. if (deepLogMode)
  656. console.log.apply(_self, arguments);
  657. }
  658.  
  659. function callbackWrapper(func)
  660. {
  661. if (typeof func !== 'function')
  662. return undefined;
  663.  
  664. return function callback()
  665. {
  666. return func.apply(_self, arguments);
  667. };
  668. }
  669.  
  670. function updateWorker()
  671. {
  672. for (let [action, name, args] of _actions) {
  673. log(_worker, action, name, args);
  674. if (action === 'set')
  675. _worker[name] = callbackWrapper(args);
  676. if (action === 'call')
  677. _worker[name].apply(_worker, args);
  678. }
  679. _actions.length = 0;
  680. log('Applied buffered actions.');
  681. }
  682.  
  683. for (let prop of _onevs.names)
  684. Object.defineProperty(_self, prop, {
  685. set: function(val) {
  686. _onevs[prop] = val;
  687. if (_worker)
  688. _worker[prop] = callbackWrapper(val);
  689. else {
  690. _actions.push(['set', prop, val]);
  691. log('Stored into buffer:', arguments);
  692. }
  693. },
  694. get: () => _onevs[prop],
  695. enumerable: true
  696. });
  697.  
  698. _self.postMessage = function()
  699. {
  700. if (_worker)
  701. _worker.postMessage.apply(_worker, arguments);
  702. else {
  703. _actions.push(['call', 'postMessage', arguments]);
  704. log('Stored into buffer:', arguments);
  705. }
  706. };
  707. _self.terminate = function()
  708. {
  709. if (_worker)
  710. _worker.terminate();
  711. else {
  712. _actions.push(['call','terminate', arguments]);
  713. log('Stored into buffer:', arguments);
  714. }
  715. };
  716. _self.addEventListener = function(event, callback, other)
  717. {
  718. if (typeof callback !== 'function')
  719. return;
  720.  
  721. if (!_callbacks.has(callback))
  722. _callbacks.set(callback, callbackWrapper(callback));
  723.  
  724. arguments[1] = _callbacks.get(callback);
  725. if (_worker)
  726. _worker.addEventListener.apply(_worker, arguments);
  727. else {
  728. _actions.push(['call', 'addEventListener', arguments]);
  729. log('Stored into buffer:', arguments);
  730. }
  731. };
  732. _self.removeEventListener = function(event, callback, other)
  733. {
  734. if (typeof callback !== 'function' || !_callbacks.has(callback))
  735. return;
  736.  
  737. arguments[1] = _callbacks.get(callback);
  738. _callbacks.delete(callback);
  739. if (_worker)
  740. _worker.removeEventListener.apply(_worker, arguments);
  741. else {
  742. _actions.push(['call', 'removeEventListener', arguments]);
  743. log('Stored into buffer:', arguments);
  744. }
  745. };
  746.  
  747. if (!isBlobURL.test(resourceURI))
  748. {
  749. _worker = new realWorker(resourceURI);
  750. return; // not a blob, no need to wrap
  751. }
  752.  
  753. (new Promise(
  754. function(resolve, reject)
  755. {
  756. let xhr = new XMLHttpRequest();
  757. xhr.responseType = 'blob';
  758. try {
  759. xhr.open('GET', resourceURI, true);
  760. } catch(e) {
  761. return reject(e);
  762. }
  763. if (xhr.readyState !== XMLHttpRequest.OPENED) {
  764. // connection wasn't opened, unable to continue wrapping procedure
  765. return reject(xhr.readyState);
  766. }
  767. xhr.onload = function(e)
  768. {
  769. if (e.target.status === 200)
  770. {
  771. let reader = new FileReader();
  772. reader.addEventListener(
  773. 'loadend', function(e)
  774. {
  775. resolve(
  776. new realWorker(URL.createObjectURL(
  777. new Blob([getWrappedCode(false) + e.target.result])
  778. ))
  779. );
  780. }, false
  781. );
  782. reader.readAsText(e.target.response);
  783. } else {
  784. return reject(e);
  785. }
  786. };
  787. xhr.onerror = (e) => reject(e);
  788. xhr.send();
  789. }
  790. )).then(
  791. function(val)
  792. {
  793. _worker = val;
  794. updateWorker();
  795. }
  796. ).catch(
  797. function(e)
  798. {
  799. // connection were blocked by CSP or something else triggered error event on xhr object
  800. // unable to proceed with wrapper, return object as-is
  801. _worker = new realWorker(resourceURI);
  802. updateWorker();
  803. }
  804. );
  805.  
  806. if (deepLogMode)
  807. {
  808. return new Proxy(_self, {
  809. get: function(target, prop) {
  810. console.log(`Get Worker.${prop}`);
  811. return target[prop];
  812. },
  813. set: function(target, prop, val) {
  814. console.log(`Set Worker.${prop} = ${val}`);
  815. target[prop] = val;
  816. return true;
  817. }
  818. });
  819. }
  820. }.bind(safeWin);
  821. }
  822.  
  823. function CreateElementWrapper()
  824. {
  825. let key = '_'+Math.random().toString(36).substr(2),
  826. _createElement = Document.prototype.createElement,
  827. _addEventListener = Element.prototype.addEventListener,
  828. isDataURL = /^data:/i,
  829. isBlobURL = /^blob:/i;
  830.  
  831. // IFrame SRC get/set wrapper
  832. let ifGetSet = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, 'src');
  833. if (ifGetSet)
  834. {
  835. let code = encodeURIComponent('<scr'+'ipt>'+getWrappedCode(true)+'</scr'+'ipt>\n'),
  836. dataSrc = new WeakMap(),
  837. _ifSet = ifGetSet.set,
  838. _ifGet = ifGetSet.get;
  839. ifGetSet.set = function(val)
  840. {
  841. if (this[key] && val === dataSrc.get(this))
  842. { // if already processed data URL then do nothing
  843. delete this[key];
  844. return null;
  845. }
  846. let isData = isDataURL.test(val);
  847. if (isData && val.indexOf(code) < 0)
  848. {
  849. dataSrc.set(this, val);
  850. val = val.replace(',',',' + code);
  851. }
  852. if (!isData && dataSrc.get(this))
  853. dataSrc.delete(this);
  854. return _ifSet.call(this, val);
  855. };
  856. ifGetSet.get = function()
  857. {
  858. return dataSrc.get(this) || _ifGet.call(this);
  859. };
  860. Object.defineProperty(HTMLIFrameElement.prototype, 'src', ifGetSet);
  861. }
  862.  
  863. function frameSetWSWrapper(e)
  864. {
  865. let frm = e.target;
  866. try {
  867. if (!frm.src || isBlobURL.test(frm.src))
  868. wrapWebSocket(frm.contentWindow);
  869. } catch (ignore) {}
  870. }
  871.  
  872. let scriptMap = new WeakMap();
  873. scriptMap.isBlocked = isBlocked;
  874. let onErrorWrapper = {
  875. set: function(val)
  876. {
  877. if (scriptMap.has(this))
  878. {
  879. this.removeEventListener('error', scriptMap.get(this).wrp, false);
  880. scriptMap.delete(this);
  881. }
  882. if (!val || typeof val !== 'function')
  883. return val;
  884.  
  885. scriptMap.set(this, {
  886. org: val,
  887. wrp: function()
  888. {
  889. if (scriptMap.isBlocked(this.src))
  890. console.log('[WSI] Blocked "onerror" callback from', this.src);
  891. else
  892. scriptMap.get(this).org.apply(this, arguments);
  893. }
  894. });
  895. this.addEventListener('error', scriptMap.get(this).wrp, false);
  896. },
  897. get: function()
  898. {
  899. return scriptMap.has(this) ? scriptMap.get(this).org : null;
  900. },
  901. enumerable: true
  902. };
  903. Document.prototype.createElement = function createElement(name) {
  904. let el = _createElement.apply(this, arguments);
  905.  
  906. if (el.tagName === 'IFRAME')
  907. _addEventListener.call(el, 'load', frameSetWSWrapper, false);
  908. if (el.tagName === 'SCRIPT')
  909. Object.defineProperty(el, 'onerror', onErrorWrapper);
  910.  
  911. return el;
  912. };
  913.  
  914. document.addEventListener(
  915. 'DOMContentLoaded', function()
  916. {
  917. for (let ifr of document.querySelectorAll('IFRAME'))
  918. {
  919. if (isDataURL.test(ifr.src))
  920. {
  921. ifr[key] = true;
  922. ifr.src = ifr.src; // call setter and let it do the job
  923. }
  924. _addEventListener.call(ifr, 'load', frameSetWSWrapper, false);
  925. }
  926. }, false
  927. );
  928. }
  929.  
  930. this.init = function()
  931. {
  932. wrapWebSocket(win);
  933. if (!(/firefox/i.test(navigator.userAgent))) // skip WorkerWrapper in Firefox
  934. (new Promise(
  935. function(resolve, reject)
  936. { // test is it possible to run inline scripts
  937. if (self.constructor.name.indexOf('Worker') > -1)
  938. return resolve(); // running within a Worker
  939. let onerr = window.onerror,
  940. onscr = (e) => resolve();
  941. // for some reason addEventListener on 'error' doesn't catch this error
  942. window.onerror = (e) => reject(e);
  943. window.addEventListener('inlineSuccess', onscr, false);
  944. let scr = document.createElement('script');
  945. scr.textContent = "window.dispatchEvent(new Event('inlineSuccess'));";
  946. document.documentElement.appendChild(scr);
  947. document.documentElement.removeChild(scr);
  948. window.removeEventListener('inlineSuccess', onscr, false);
  949. window.onerror = onerr;
  950. }
  951. )).then(
  952. (e) => WorkerWrapper()
  953. ).catch(
  954. (e) => console.log('[WSI] Unable to create inline script. Skipping Worker wrapper to avoid further issues.', e)
  955. );
  956. if (typeof document !== 'undefined')
  957. CreateElementWrapper();
  958. };
  959. }
  960.  
  961. if (isFirefox)
  962. {
  963. let script = _createElement('script');
  964. script.textContent = getWrappedCode(true);
  965. _appendChild(script);
  966. _removeChild(script);
  967. return; //we don't want to call functions on page from here in Fx, so exit
  968. }
  969.  
  970. (new WSI((unsafeWindow||self||window),(self||window))).init();
  971. }
  972.  
  973. if (!isFirefox)
  974. { // scripts for non-Firefox browsers
  975. // https://greasyfork.org/scripts/14720-it-s-not-important
  976. {
  977. let imptt = /((display|(margin|padding)(-top|-bottom)?)\s*:[^;!]*)!\s*important/ig,
  978. ret_b = (a,b) => b,
  979. _toLowerCase = String.prototype.toLowerCase,
  980. protectedNodes = new WeakSet(),
  981. log = false;
  982.  
  983. let logger = function()
  984. {
  985. if (log)
  986. console.log('Some page elements became a bit less important.');
  987. log = false;
  988. };
  989.  
  990. let unimportanter = function(node)
  991. {
  992. let style = (node.nodeType === Node.ELEMENT_NODE) ?
  993. _getAttribute.call(node, 'style') : null;
  994.  
  995. if (!style || !imptt.test(style) || node.style.display === 'none' ||
  996. (node.src && node.src.slice(0,17) === 'chrome-extension:')) // Web of Trust IFRAME and similar
  997. return false; // get out if we have nothing to do here
  998.  
  999. protectedNodes.add(node);
  1000. _setAttribute.call(node, 'style',
  1001. style.replace(imptt, ret_b));
  1002. log = true;
  1003. };
  1004.  
  1005. (new MutationObserver(
  1006. function(mutations)
  1007. {
  1008. setTimeout(
  1009. function(ms)
  1010. {
  1011. let m, node;
  1012. for (m of ms) for (node of m.addedNodes)
  1013. unimportanter(node);
  1014. logger();
  1015. }, 0, mutations
  1016. );
  1017. }
  1018. )).observe(document, {
  1019. childList : true,
  1020. subtree : true
  1021. });
  1022.  
  1023. Element.prototype.setAttribute = function setAttribute(name, value)
  1024. {
  1025. "[native code]";
  1026. let replaced = value;
  1027. if (_toLowerCase.call(name) === 'style' && protectedNodes.has(this))
  1028. replaced = value.replace(imptt, ret_b);
  1029. log = (replaced !== value);
  1030. logger();
  1031. return _setAttribute.call(this, name, replaced);
  1032. };
  1033.  
  1034. win.addEventListener (
  1035. 'load', function()
  1036. {
  1037. for (let imp of document.querySelectorAll('[style*="!"]'))
  1038. unimportanter(imp);
  1039. logger();
  1040. }, false
  1041. );
  1042. }
  1043.  
  1044. // Naive ABP Style protector
  1045. {
  1046. let _querySelector = Document.prototype.querySelector.bind(document);
  1047. let _removeChild = Node.prototype.removeChild;
  1048. let _appendChild = Node.prototype.appendChild;
  1049. let createShadow = () => _createElement('shadow');
  1050. // Prevent adding fake content entry point
  1051. Node.prototype.appendChild = function(child)
  1052. {
  1053. if (this instanceof ShadowRoot &&
  1054. child instanceof HTMLContentElement)
  1055. return _appendChild.call(this, createShadow());
  1056. return _appendChild.apply(this, arguments);
  1057. };
  1058. {
  1059. let _shadowSelector = ShadowRoot.prototype.querySelector;
  1060. let _innerHTML = Object.getOwnPropertyDescriptor(ShadowRoot.prototype, 'innerHTML');
  1061. let _parentNode = Object.getOwnPropertyDescriptor(Node.prototype, 'parentNode');
  1062. if (_innerHTML && _parentNode)
  1063. {
  1064. let _set = _innerHTML.set;
  1065. let _getParent = _parentNode.get;
  1066. _innerHTML.configurable = false;
  1067. _innerHTML.set = function()
  1068. {
  1069. _set.apply(this, arguments);
  1070. let content = _shadowSelector.call(this, 'content');
  1071. if (content)
  1072. {
  1073. let parent = _getParent.call(content);
  1074. _removeChild.call(parent, content);
  1075. _appendChild.call(parent, createShadow());
  1076. }
  1077. };
  1078. }
  1079. Object.defineProperty(ShadowRoot.prototype, 'innerHTML', _innerHTML);
  1080. }
  1081. // Locate and apply extra protection to a style on top of what ABP does
  1082. let style;
  1083. (new Promise(
  1084. function(resolve, reject)
  1085. {
  1086. let getStyle = () => _querySelector('::shadow style');
  1087. style = getStyle();
  1088. if (style)
  1089. return resolve(style);
  1090. let intv = setInterval(
  1091. function()
  1092. {
  1093. style = getStyle();
  1094. if (!style)
  1095. return;
  1096. intv = clearInterval(intv);
  1097. return resolve(style);
  1098. }, 0
  1099. );
  1100. document.addEventListener(
  1101. 'DOMContentLoaded',
  1102. function()
  1103. {
  1104. if (intv)
  1105. clearInterval(intv);
  1106. style = getStyle();
  1107. return style ? resolve(style) : reject();
  1108. },
  1109. false
  1110. );
  1111. }
  1112. )).then(
  1113. function(style)
  1114. {
  1115. let emptyArr = [],
  1116. nullStr = {
  1117. get: () => '',
  1118. set: () => undefined
  1119. };
  1120. Object.defineProperties(style, {
  1121. innerHTML: nullStr,
  1122. textContent: nullStr
  1123. });
  1124. Object.defineProperties(style.sheet, {
  1125. deleteRule: () => null,
  1126. cssRules: emptyArr,
  1127. rules: emptyArr
  1128. });
  1129. }
  1130. ).catch(()=>null);
  1131. Node.prototype.removeChild = function(child)
  1132. {
  1133. if (child === style)
  1134. return;
  1135. return _removeChild.apply(this, arguments);
  1136. };
  1137. }
  1138. }
  1139. if (/^https?:\/\/(mail\.yandex\.|music\.yandex\.|news\.yandex\.|(www\.)?yandex\.[^\/]+\/(yand)?search[\/?])/i.test(win.location.href) ||
  1140. /^https?:\/\/tv\.yandex\./i.test(win.location.href))
  1141. {
  1142. // https://greasyfork.org/en/scripts/809-no-yandex-ads
  1143. let _querySelector = document.querySelector.bind(document),
  1144. _querySelectorAll = document.querySelectorAll.bind(document),
  1145. _getAttribute = Element.prototype.getAttribute,
  1146. _setAttribute = Element.prototype.setAttribute,
  1147. _attachShadow = Element.prototype.attachShadow,
  1148. _getShadowRoot = Object.getOwnPropertyDescriptor(Element.prototype, 'shadowRoot').get;
  1149. document.addEventListener(
  1150. 'DOMContentLoaded', function()
  1151. {
  1152. let adWords = [/Яндекс.Директ/i, /Реклама/i, /Ad/i],
  1153. genericAdSelectors = (
  1154. '.serp-adv__head + .serp-item,'+
  1155. '#adbanner,'+
  1156. '.serp-adv,'+
  1157. '.b-spec-adv,'+
  1158. 'div[class*="serp-adv__"]:not(.serp-adv__found):not(.serp-adv__displayed)'
  1159. );
  1160. // Generic ads removal and fixes
  1161. {
  1162. let node = _querySelector('.serp-header');
  1163. if (node)
  1164. node.style.marginTop = '0';
  1165. for (node of _querySelectorAll(genericAdSelectors))
  1166. remove(node);
  1167. }
  1168. // Short name for parentNode.removeChild
  1169. function remove(node) {
  1170. if (!node || !node.parentNode)
  1171. return false;
  1172. console.log('Removed node.');
  1173. node.parentNode.removeChild(node);
  1174. }
  1175. // Short name to hide node with style attribute
  1176. let hiddenNodes = new WeakSet();
  1177. function hide(node) {
  1178. if (hiddenNodes.has(node))
  1179. return false;
  1180. _setAttribute.call(node, 'style', 'display: none !important');
  1181. hiddenNodes.add(node);
  1182. console.log('Hid node.');
  1183. return true;
  1184. }
  1185. // Search ads
  1186. function removeSearchAds()
  1187. {
  1188. let res = false;
  1189. // hide unparsed Yandex ads if present
  1190. for (let node of _querySelectorAll('.serp-item[role="complementary"]'))
  1191. res = res|hide(node);
  1192. if (res) return 'Unparsed Yandex ads were hidden.';
  1193. // hide parsed Yandex ads
  1194. let nodes = _querySelectorAll('.serp-item .organic'),
  1195. path, label, openShadow = { mode: 'open' },
  1196. root = (node) => node.closest('.serp-item');
  1197. for (let node of nodes)
  1198. {
  1199. label = node.querySelector('.path ~ :last-child');
  1200. try {
  1201. if (!_getShadowRoot.call(label))
  1202. _attachShadow.call(label, openShadow);
  1203. } catch (e) {
  1204. res = res|hide(root(node));
  1205. continue;
  1206. }
  1207. label = node.querySelector('.label');
  1208. if (label && (adWords[1].test(label.textContent) || adWords[2].test(label.textContent)))
  1209. res = res|hide(root(node));
  1210. }
  1211. if (res)
  1212. return 'Parsed Yandex ads were hidden.';
  1213. else
  1214. return 'No ads were detected.';
  1215. }
  1216. function removeSearchAdsLog()
  1217. {
  1218. let res = removeSearchAds();
  1219. if (res) console.log(res);
  1220. }
  1221. // News ads
  1222. function removeNewsAds()
  1223. {
  1224. let node, block, item, items, mask, classes,
  1225. masks = [
  1226. { class: '.ads__wrapper', regex: /[^,]*?,[^,]*?\.ads__wrapper/ },
  1227. { class: '.ads__pool', regex: /[^,]*?,[^,]*?\.ads__pool/ }
  1228. ];
  1229. for (node of _querySelectorAll('style[nonce]'))
  1230. {
  1231. classes = node.innerText.replace(/\{[^}]+\}+/ig, '|').split('|');
  1232. for (block of classes) for (mask of masks)
  1233. if (block.includes(mask.class))
  1234. {
  1235. block = block.match(mask.regex)[0];
  1236. items = _querySelectorAll(block);
  1237. for (item of items)
  1238. remove(items[0]);
  1239. }
  1240. }
  1241. }
  1242. // Music ads
  1243. function removeMusicAds()
  1244. {
  1245. for (let node of _querySelectorAll('.ads-block'))
  1246. remove(node);
  1247. }
  1248. // Mail ads
  1249. function removeMailAds()
  1250. {
  1251. let slice = Array.prototype.slice,
  1252. nodes = slice.call(_querySelectorAll('.ns-view-folders')),
  1253. node, len, cls;
  1254.  
  1255. for (node of nodes)
  1256. if (!len || len > node.classList.length)
  1257. len = node.classList.length;
  1258.  
  1259. node = nodes.pop();
  1260. while (node)
  1261. {
  1262. if (node.classList.length > len)
  1263. for (cls of slice.call(node.classList))
  1264. if (cls.indexOf('-') === -1)
  1265. {
  1266. remove(node);
  1267. break;
  1268. }
  1269. node = nodes.pop();
  1270. }
  1271. }
  1272. // News fixes
  1273. function removePageAdsClass()
  1274. {
  1275. if (document.body.classList.contains("b-page_ads_yes"))
  1276. {
  1277. document.body.classList.remove("b-page_ads_yes");
  1278. console.log('Page ads class removed.');
  1279. }
  1280. }
  1281. // TV fixes
  1282. function removeTVAds()
  1283. {
  1284. for (let node of _querySelectorAll('div[class^="_"][data-reactid] > div'))
  1285. if (adWords[0].test(node.textContent) || node.querySelector('iframe:not([src])'))
  1286. {
  1287. if (node.offsetWidth)
  1288. {
  1289. let pad = document.createElement('div');
  1290. _setAttribute.call(pad, 'style', 'width:'+node.offsetWidth+'px');
  1291. node.parentNode.appendChild(pad);
  1292. }
  1293. remove(node);
  1294. }
  1295. }
  1296. // Function to attach an observer to monitor dynamic changes on the page
  1297. function pageUpdateObserver(func, obj, params) {
  1298. if (obj)
  1299. (new MutationObserver(func))
  1300. .observe(obj, (params || { childList:true, subtree:true }));
  1301. }
  1302.  
  1303. if (location.hostname.startsWith('mail.')) {
  1304. pageUpdateObserver(
  1305. function(ms, o)
  1306. {
  1307. let aside = _querySelector('.mail-Layout-Aside');
  1308. if (aside) {
  1309. o.disconnect();
  1310. pageUpdateObserver(removeMailAds, aside);
  1311. }
  1312. }, document.body
  1313. );
  1314. removeMailAds();
  1315. } else if (location.hostname.startsWith('music.')) {
  1316. pageUpdateObserver(removeMusicAds, _querySelector('.sidebar'));
  1317. removeMusicAds();
  1318. } else if (location.hostname.startsWith('news.')) {
  1319. pageUpdateObserver(removeNewsAds, document.body);
  1320. pageUpdateObserver(removePageAdsClass, document.body, { attributes:true, attributesFilter:['class'] });
  1321. removeNewsAds();
  1322. removePageAdsClass();
  1323. } else if (location.hostname.startsWith('tv.')) {
  1324. pageUpdateObserver(removeTVAds, document.body);
  1325. removeTVAds();
  1326. } else {
  1327. pageUpdateObserver(removeSearchAdsLog, _querySelector('.main__content'));
  1328. removeSearchAdsLog();
  1329. }
  1330. }
  1331. );
  1332. }
  1333.  
  1334. // Yandex Link Tracking
  1335. if (/^https?:\/\/([^.]+\.)*yandex\.[^\/]+/i.test(win.location.href))
  1336. {
  1337. let fakeRoot = {
  1338. firstChild: null,
  1339. appendChild: ()=>null,
  1340. querySelector: ()=>null,
  1341. querySelectorAll: ()=>null
  1342. };
  1343. Element.prototype.createShadowRoot = () => fakeRoot;
  1344. Object.defineProperty(Element.prototype, "shadowRoot", {
  1345. value: fakeRoot,
  1346. enumerable: true,
  1347. configurable: false
  1348. });
  1349. // Partially based on https://greasyfork.org/en/scripts/22737-remove-yandex-redirect
  1350. let selectors = (
  1351. 'A[onmousedown*="/jsredir"],'+
  1352. 'A[data-vdir-href],'+
  1353. 'A[data-counter]'
  1354. );
  1355. let removeTrackingAttributes = function(link)
  1356. {
  1357. link.removeAttribute('onmousedown');
  1358. if (link.hasAttribute('data-vdir-href')) {
  1359. link.removeAttribute('data-vdir-href');
  1360. link.removeAttribute('data-orig-href');
  1361. }
  1362. if (link.hasAttribute('data-counter')) {
  1363. link.removeAttribute('data-counter');
  1364. link.removeAttribute('data-bem');
  1365. }
  1366. };
  1367. let removeTracking = function(scope)
  1368. {
  1369. for (let link of scope.querySelectorAll(selectors))
  1370. removeTrackingAttributes(link);
  1371. };
  1372. document.addEventListener('DOMContentLoaded', (e) => removeTracking(e.target));
  1373. (new MutationObserver(
  1374. function(ms)
  1375. {
  1376. let m, node;
  1377. for (m of ms) for (node of m.addedNodes) if (node.nodeType === Node.ELEMENT_NODE)
  1378. if (node.tagName === 'A' && node.matches(selectors)) {
  1379. removeTrackingAttributes(node);
  1380. } else {
  1381. removeTracking(node);
  1382. }
  1383. }
  1384. )).observe(_de, { childList: true, subtree: true });
  1385.  
  1386. //skip fixes for other sites
  1387. return;
  1388. }
  1389.  
  1390. // https://greasyfork.org/en/scripts/21937-moonwalk-hdgo-kodik-fix v0.8 (adapted)
  1391. document.addEventListener(
  1392. 'DOMContentLoaded', function()
  1393. {//createPlayer();
  1394. function log (name) {
  1395. console.log(`Player FIX: Detected ${name} player in ${location.href}`);
  1396. }
  1397. if (win.adv_enabled !== undefined && win.condition_detected !== undefined)
  1398. {
  1399. log('Moonwalk');
  1400. if (win.adv_enabled)
  1401. win.adv_enabled = false;
  1402. win.condition_detected = false;
  1403. if (win.MXoverrollCallback)
  1404. document.addEventListener(
  1405. 'click', function catcher(e)
  1406. {
  1407. e.stopPropagation();
  1408. win.MXoverrollCallback.call(window);
  1409. document.removeEventListener('click', catcher, true);
  1410. }, true
  1411. );
  1412. }
  1413. else if (win.stat_url !== undefined && win.is_html5 !== undefined && win.is_wp8 !== undefined)
  1414. {
  1415. log('HDGo');
  1416. document.body.onclick = null;
  1417. let tmp = document.querySelector('#swtf');
  1418. if (tmp)
  1419. tmp.style.display = 'none';
  1420. if (win.banner_second !== undefined)
  1421. win.banner_second = 0;
  1422. if (win.$banner_ads !== undefined)
  1423. win.$banner_ads = false;
  1424. if (win.$new_ads !== undefined)
  1425. win.$new_ads = false;
  1426. if (win.createCookie !== undefined)
  1427. win.createCookie('popup', 'true', '999');
  1428. if (win.canRunAds !== undefined && win.canRunAds !== true)
  1429. win.canRunAds = true;
  1430. }
  1431. else if (win.MXoverrollCallback && win.iframeSearch !== undefined)
  1432. {
  1433. log('Kodik');
  1434. let tmp = document.querySelector('.play_button');
  1435. if (tmp)
  1436. tmp.onclick = win.MXoverrollCallback.bind(window);
  1437. win.IsAdBlock = false;
  1438. }
  1439. else if (win.getnextepisode && win.uppodEvent)
  1440. {
  1441. log('Share-Serials.net');
  1442. scriptLander(
  1443. function()
  1444. {
  1445. let _setInterval = win.setInterval,
  1446. _setTimeout = win.setTimeout;
  1447. win.setInterval = function(func)
  1448. {
  1449. if (func instanceof Function && func.toString().indexOf('_delay') > -1)
  1450. {
  1451. let intv = _setInterval.call(
  1452. this, function()
  1453. {
  1454. _setTimeout.call(
  1455. this, function(intv)
  1456. {
  1457. clearInterval(intv);
  1458. let timer = document.querySelector('#timer');
  1459. if (timer)
  1460. timer.click();
  1461. }, 100, intv);
  1462. func.call(this);
  1463. }, 5
  1464. );
  1465.  
  1466. return intv;
  1467. }
  1468. return _setInterval.apply(this, arguments);
  1469. };
  1470. win.setTimeout = function(func) {
  1471. if (func instanceof Function && func.toString().indexOf('adv_showed') > -1)
  1472. {
  1473. return _setTimeout.call(this, func, 0);
  1474. }
  1475. return _setTimeout.apply(this, arguments);
  1476. };
  1477. }
  1478. );
  1479. }
  1480. }, false
  1481. );
  1482.  
  1483. // piguiqproxy.com circumvention prevention
  1484. scriptLander(
  1485. function()
  1486. {
  1487. let _open = XMLHttpRequest.prototype.open;
  1488. let blacklist = /[/.@](piguiqproxy\.com|rcdn\.pro)[:/]/i;
  1489. XMLHttpRequest.prototype.open = function(method, url)
  1490. {
  1491. if (method === 'GET' && blacklist.test(url))
  1492. {
  1493. this.send = () => null;
  1494. this.setRequestHeader = () => null;
  1495. console.log('Blocked request: ', url);
  1496. return;
  1497. }
  1498. return _open.apply(this, arguments);
  1499. };
  1500. }
  1501. );
  1502.  
  1503. // === Helper functions ===
  1504.  
  1505. // function to search and remove nodes by content
  1506. // selector - standard CSS selector to define set of nodes to check
  1507. // words - regular expression to check content of the suspicious nodes
  1508. // params - object with multiple extra parameters:
  1509. // .log - display log in the console
  1510. // .hide - set display to none instead of removing from the page
  1511. // .parent - parent node to remove if content is found in the child node
  1512. // .siblings - number of simling nodes to remove (excluding text nodes)
  1513. let scRemove = (node) => node.parentNode.removeChild(node);
  1514. let scHide = function(node)
  1515. {
  1516. let style = _getAttribute.call(node, 'style') || '',
  1517. hide = ';display:none!important;';
  1518. if (style.indexOf(hide) < 0)
  1519. _setAttribute.call(node, 'style', style + hide);
  1520. };
  1521.  
  1522. function scissors (selector, words, scope, params)
  1523. {
  1524. let logger = function() { return params.log ? console.log(...arguments) : null; };
  1525. if (!scope.contains(document.body))
  1526. logger('[s] scope', scope);
  1527. let remFunc = (params.hide ? scHide : scRemove),
  1528. iterFunc = (params.siblings > 0 ? 'nextSibling' : 'previousSibling'),
  1529. toRemove = [],
  1530. siblings;
  1531. for (let node of scope.querySelectorAll(selector))
  1532. {
  1533. // drill up to a parent node if specified, break if not found
  1534. if (params.parent)
  1535. {
  1536. let old = node;
  1537. node = node.closest(params.parent);
  1538. if (node === null || node.contains(scope))
  1539. {
  1540. logger('[s] went out of scope with', old);
  1541. break;
  1542. }
  1543. }
  1544. logger('[s] processing', node);
  1545. if (words.test(node.innerHTML) || !node.childNodes.length)
  1546. {
  1547. // drill across for N sibling nodes
  1548. if (!toRemove.includes(node))
  1549. {
  1550. logger('[s] marked for removal');
  1551. toRemove.push(node);
  1552. // add multiple nodes if defined more than one sibling
  1553. siblings = Math.abs(params.siblings) || 0;
  1554. while (siblings)
  1555. {
  1556. node = node[iterFunc];
  1557. if (node.nodeType === Node.ELEMENT_NODE)
  1558. {
  1559. logger('[s] adding sibling node', node);
  1560. toRemove.push(node);
  1561. siblings -= 1; //count only element nodes
  1562. }
  1563. else if (!params.hide)
  1564. {
  1565. logger('[s] adding sibling node', node);
  1566. toRemove.push(node);
  1567. }
  1568. }
  1569. }
  1570. }
  1571. }
  1572. if (toRemove.length)
  1573. {
  1574. logger(`[s] proceeding with ${params.hide?'hide':'removal'} of`, toRemove);
  1575. for (let node of toRemove)
  1576. remFunc(node);
  1577. }
  1578.  
  1579. return toRemove.length;
  1580. }
  1581.  
  1582. // function to perform multiple checks if ads inserted with a delay
  1583. // by default does 30 checks withing a 3 seconds unless nonstop mode specified
  1584. // also does 1 extra check when a page completely loads
  1585. // selector and words - passed dow to scissors
  1586. // params - object with multiple extra parameters:
  1587. // .log - display log in the console
  1588. // .root - selector to narrow down scope to scan;
  1589. // .observe - if true then check will be performed continuously;
  1590. // Other parameters passed down to scissors.
  1591. function gardener(selector, words, params)
  1592. {
  1593. let logger = function() { return params.log ? console.log(...arguments) : null; };
  1594. params = params || {};
  1595. logger(`[gardener] selector: '${selector}' detector: ${words} options: ${JSON.stringify(params)}`);
  1596. let scope = [document];
  1597. function onevent(e)
  1598. {
  1599. logger(`[gardener] cleanup on ${e.constructor.name.replace('Object', 'Event')} "${e.type}"`);
  1600. for (let node of scope)
  1601. scissors(selector, words, node, params);
  1602. }
  1603. document.addEventListener(
  1604. 'DOMContentLoaded', (e) => {
  1605. // narrow down scope to a specific element
  1606. if (params.root)
  1607. {
  1608. scope = document.querySelectorAll(params.root);
  1609. if (!scope) // exit if the root element is not present on the page
  1610. return 0;
  1611. }
  1612. logger('[g] scope', scope);
  1613. // add observe mode if required
  1614. if (params.observe)
  1615. {
  1616. let params = { childList:true, subtree: true };
  1617. let observer = new MutationObserver(
  1618. function(ms)
  1619. {
  1620. for (let m of ms)
  1621. if (m.addedNodes.length)
  1622. onevent(m);
  1623. }
  1624. );
  1625. for (let node of scope)
  1626. observer.observe(node, params);
  1627. logger('[g] observer enabled');
  1628. }
  1629. onevent(e);
  1630. }, false);
  1631. // wait for a full page load to do one extra cut
  1632. win.addEventListener('load', onevent, false);
  1633. }
  1634.  
  1635. // wrap popular methods to open a new tab to catch specific behaviours
  1636. function createWindowOpenWrapper(openFunc, onClickFunc)
  1637. {
  1638. let _createElement = Document.prototype.createElement,
  1639. _appendChild = Element.prototype.appendChild,
  1640. fakeNative = (f) => (f.toString = () => 'function '+f.name+'() { [native code] }');
  1641.  
  1642. let nt = new nullTools();
  1643. fakeNative(openFunc);
  1644. function redefineOpen(obj)
  1645. {
  1646. nt.define(obj, 'open', openFunc);
  1647. nt.define(obj.document, 'open', openFunc);
  1648. nt.define(obj.Document.prototype, 'open', openFunc);
  1649. }
  1650. redefineOpen(win);
  1651.  
  1652. function createElement(name)
  1653. {
  1654. '[native code]';
  1655. // jshint validthis:true
  1656. let el = _createElement.apply(this, arguments);
  1657. // click-dispatch check for Google Chrome and similar browsers
  1658. if (el instanceof HTMLAnchorElement)
  1659. el.addEventListener(
  1660. 'click', onClickFunc, false
  1661. );
  1662. // redefine window.open in first-party frames
  1663. if (el instanceof HTMLIFrameElement || el instanceof HTMLObjectElement)
  1664. el.addEventListener(
  1665. 'load', function(e)
  1666. {
  1667. try {
  1668. redefineOpen(e.target.contentWindow);
  1669. } catch(ignore) {}
  1670. }, false
  1671. );
  1672. return el;
  1673. }
  1674. fakeNative(createElement);
  1675.  
  1676. function redefineCreateElement(obj)
  1677. {
  1678. nt.define(obj.document, 'createElement', createElement);
  1679. nt.define(obj.Document.prototype, 'createElement', createElement);
  1680. }
  1681. redefineCreateElement(win);
  1682.  
  1683. // wrap window.open in newly added first-party frames
  1684. Element.prototype.appendChild = function appendChild()
  1685. {
  1686. '[native code]';
  1687. let el = _appendChild.apply(this, arguments);
  1688. if (el instanceof HTMLIFrameElement) {
  1689. try {
  1690. redefineOpen(el.contentWindow);
  1691. redefineCreateElement(el.contentWindow);
  1692. } catch(ignore) {}
  1693. }
  1694. return el;
  1695. };
  1696. fakeNative(Element.prototype.appendChild);
  1697. }
  1698.  
  1699. // Function to catch and block various methods to open a new window with 3rd-party content.
  1700. // Some advertisement networks went way past simple window.open call to circumvent default popup protection.
  1701. // This funciton blocks window.open, ability to restore original window.open from an IFRAME object,
  1702. // ability to perform an untrusted (not initiated by user) click on a link, click on a link without a parent
  1703. // node or simply a link with piece of javascript code in the HREF attribute.
  1704. function preventPopups()
  1705. {
  1706. if (inIFrame)
  1707. {
  1708. win.top.postMessage({ name: 'sandbox-me', href: win.location.href }, '*');
  1709. return;
  1710. }
  1711.  
  1712. scriptLander(
  1713. function()
  1714. {
  1715. function open()
  1716. {
  1717. '[native code]';
  1718. console.log('Site attempted to open a new window', arguments);
  1719. return {
  1720. document: {
  1721. write: () => {},
  1722. writeln: () => {}
  1723. }
  1724. };
  1725. }
  1726.  
  1727. function clickHandler(e)
  1728. {
  1729. let link = e.target;
  1730. if (!link.parentNode || !e.isTrusted ||
  1731. (link.href && link.href.trim().toLowerCase().indexOf('javascript') === 0))
  1732. {
  1733. e.preventDefault();
  1734. console.log('Blocked suspicious click event', e, 'on', e.target);
  1735. }
  1736. }
  1737.  
  1738. createWindowOpenWrapper(open, clickHandler);
  1739.  
  1740. console.log('Popup prevention enabled.');
  1741. }, [nullTools, createWindowOpenWrapper]
  1742. );
  1743. }
  1744.  
  1745. // Helper function to close background tab if site opens itself in a new tab and then
  1746. // loads a 3rd-party page in the background one (thus performing background redirect).
  1747. function preventPopunders()
  1748. {
  1749. // create "close_me" event to call high-level window.close()
  1750. let eventName = 'close_me_' + Math.random().toString(36).substr(2);
  1751. let callClose = () => (console.log('close call'), window.close());
  1752. window.addEventListener(eventName, callClose, true);
  1753.  
  1754. scriptLander(
  1755. function()
  1756. {
  1757. let _open = window.open,
  1758. parseURL = document.createElement('A');
  1759. // get host of a provided URL with help of an anchor object
  1760. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  1761. let getHost = (url) => (parseURL.href = url, parseURL.host);
  1762. // site went to a new tab and attempts to unload
  1763. // call for high-level close through event
  1764. let closeWindow = () => window.dispatchEvent(new CustomEvent(eventName, {}));
  1765. // check is URL local or goes to different site
  1766. function isLocal(url)
  1767. {
  1768. let loc = window.location;
  1769. if (url === loc.pathname || url === loc.href)
  1770. return true; // URL points to current pathname or full address
  1771. let host = getHost(url),
  1772. site = loc.host;
  1773. if (host === '')
  1774. return false; // URLs with unusual protocol may have empty 'host'
  1775. if (host.length > site.length)
  1776. [site, host] = [host, site];
  1777. return site.includes(host, site.length - host.length);
  1778. }
  1779.  
  1780. function open(url)
  1781. {
  1782. '[native code]';
  1783. if (url && isLocal(url))
  1784. window.addEventListener('unload', closeWindow, true);
  1785. // jshint validthis:true
  1786. return _open.apply(this, arguments);
  1787. }
  1788.  
  1789. function clickHandler(e)
  1790. {
  1791. if (!e.target.parentNode || !e.isTrusted)
  1792. window.addEventListener('unload', closeWindow, true);
  1793. }
  1794.  
  1795. createWindowOpenWrapper(open, clickHandler);
  1796.  
  1797. console.log("Background redirect prevention enabled.");
  1798. }, [nullTools, createWindowOpenWrapper, 'let eventName="'+eventName+'"']
  1799. );
  1800. }
  1801.  
  1802. // Mix between check for popups and popunders
  1803. // Significantly more agressive than both and can't be used as universal solution
  1804. function preventPopMix()
  1805. {
  1806. if (inIFrame)
  1807. {
  1808. win.top.postMessage({ name: 'sandbox-me', href: win.location.href }, '*');
  1809. return;
  1810. }
  1811.  
  1812. // create "close_me" event to call high-level window.close()
  1813. let eventName = 'close_me_' + Math.random().toString(36).substr(2);
  1814. let callClose = () => (console.log('close call'), window.close());
  1815. window.addEventListener(eventName, callClose, true);
  1816.  
  1817. scriptLander(
  1818. function()
  1819. {
  1820. let _open = window.open,
  1821. parseURL = document.createElement('A');
  1822. // get host of a provided URL with help of an anchor object
  1823. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  1824. let getHost = (url) => (parseURL.href = url, parseURL.host);
  1825. // site went to a new tab and attempts to unload
  1826. // call for high-level close through event
  1827. let closeWindow = () => (_open(window.location,'_self'), window.dispatchEvent(new CustomEvent(eventName, {})));
  1828. // check is URL local or goes to different site
  1829. function isLocal(url)
  1830. {
  1831. let loc = window.location;
  1832. if (url === loc.pathname || url === loc.href)
  1833. return true; // URL points to current pathname or full address
  1834. let host = getHost(url),
  1835. site = loc.host;
  1836. if (host === '')
  1837. return false; // URLs with unusual protocol may have empty 'host'
  1838. if (host.length > site.length)
  1839. [site, host] = [host, site];
  1840. return site.includes(host, site.length - host.length);
  1841. }
  1842.  
  1843. // add check for redirect for 5 seconds, then disable it
  1844. function checkRedirect()
  1845. {
  1846. window.addEventListener('unload', closeWindow, true);
  1847. setTimeout(closeWindow=>window.removeEventListener('unload', closeWindow, true), 5000, closeWindow);
  1848. }
  1849.  
  1850. function open(url, name)
  1851. {
  1852. '[native code]';
  1853. if (url && isLocal(url) && (!name || name === '_blank'))
  1854. {
  1855. console.trace('Suspicious local new window', arguments);
  1856. checkRedirect();
  1857. // jshint validthis:true
  1858. return _open.apply(this, arguments);
  1859. }
  1860. console.trace('Blocked attempt to open a new window', arguments);
  1861. return {
  1862. document: {
  1863. write: () => {},
  1864. writeln: () => {}
  1865. }
  1866. };
  1867. }
  1868.  
  1869. function clickHandler(e)
  1870. {
  1871. let link = e.target,
  1872. url = link.href||'';
  1873. if (e.targetParentNode && e.isTrusted || link.target !== '_blank')
  1874. {
  1875. console.log('Link', link, 'were created dinamically, but looks fine.');
  1876. return true;
  1877. }
  1878. if (isLocal(url) && link.target === '_blank')
  1879. {
  1880. console.log('Suspicious local link', link);
  1881. checkRedirect();
  1882. return;
  1883. }
  1884. console.log('Blocked suspicious click on a link', link);
  1885. e.stopPropagation();
  1886. e.preventDefault();
  1887. }
  1888.  
  1889. createWindowOpenWrapper(open, clickHandler);
  1890.  
  1891. console.log("Mixed popups prevention enabled.");
  1892. }, [createWindowOpenWrapper, 'let eventName="'+eventName+'"']
  1893. );
  1894. }
  1895. // External listener for case when site known to open popups were loaded in iframe
  1896. // It will sandbox any iframe which will send message 'forbid.popups' (preventPopups sends it)
  1897. // Some sites replace frame's window.location with data-url to run in clean context
  1898. if (!inIFrame)
  1899. {
  1900. window.addEventListener(
  1901. 'message', function(e)
  1902. {
  1903. if (!e.data || e.data.name !== 'sandbox-me' || !e.data.href)
  1904. return;
  1905. let src = e.data.href;
  1906. for (let frame of document.querySelectorAll('iframe'))
  1907. if (frame.contentWindow === e.source)
  1908. {
  1909. if (frame.hasAttribute('sandbox'))
  1910. {
  1911. if (!frame.sandbox.contains('allow-popups'))
  1912. return; // exit frame since it's already sandboxed and popups are blocked
  1913. // remove allow-popups if frame already sandboxed
  1914. frame.sandbox.remove('allow-popups');
  1915. } else {
  1916. // set sandbox mode for troublesome frame and allow scripts, forms and a few other actions
  1917. // technically allowing both scripts and same-origin allows removal of the sandbox attribute,
  1918. // but to apply content must be reloaded and this script will re-apply it in the result
  1919. frame.setAttribute('sandbox','allow-forms allow-scripts allow-presentation allow-top-navigation allow-same-origin');
  1920. }
  1921. console.log('Disallowed popups from iframe', frame);
  1922.  
  1923. // reload frame content to apply restrictions
  1924. if (!src) {
  1925. src = frame.src;
  1926. console.log('Unable to get current iframe location, reloading from src', src);
  1927. } else
  1928. console.log('Reloading iframe with URL', src);
  1929. frame.src = 'about:blank';
  1930. frame.src = src;
  1931. }
  1932. }, false
  1933. );
  1934. }
  1935.  
  1936. // === Scripts for specific domains ===
  1937.  
  1938. let scripts = {};
  1939. // prevent popups and redirects block
  1940. // Popups
  1941. scripts.preventPopups = {
  1942. other: [
  1943. 'biqle.ru',
  1944. 'chaturbate.com',
  1945. 'dfiles.ru',
  1946. 'hentaiz.org',
  1947. 'mirrorcreator.com',
  1948. 'online-multy.ru',
  1949. 'radikal.ru',
  1950. 'seedoff.cc', 'seedoff.tv',
  1951. 'tapochek.net', 'thepiratebay.org', 'torseed.net',
  1952. 'unionpeer.com',
  1953. 'zippyshare.com'
  1954. ],
  1955. now: preventPopups
  1956. };
  1957. // Popunders (background redirect)
  1958. scripts.preventPopunders = {
  1959. other: [
  1960. 'mediafire.com', 'megapeer.org', 'megapeer.ru',
  1961. 'perfectgirls.net'
  1962. ],
  1963. now: preventPopunders
  1964. };
  1965. // PopMix (both types of popups encountered on site)
  1966. scripts['openload.co'] = {
  1967. other: ['oload.tv', 'oload.info'],
  1968. now: () => {
  1969. let nt = new nullTools();
  1970. nt.define(win, 'CNight', win.CoinHive);
  1971. if (location.pathname.startsWith('/embed/'))
  1972. {
  1973. nt.define(win, 'BetterJsPop', {
  1974. add: ((a, b) => console.trace('BetterJsPop.add', a, b)),
  1975. config: ((o) => console.trace('BetterJsPop.config', o)),
  1976. Browser: { isChrome: true }
  1977. });
  1978. nt.define(win, 'isSandboxed', nt.func(null));
  1979. nt.define(win, 'adblock', false);
  1980. nt.define(win, 'adblock2', false);
  1981. } else
  1982. preventPopMix();
  1983. }
  1984. };
  1985. scripts['turbobit.net'] = preventPopMix;
  1986.  
  1987. // other
  1988. scripts['2picsun.ru'] = {
  1989. other: [
  1990. 'pics2sun.ru', '3pics-img.ru'
  1991. ],
  1992. now: () => {
  1993. Object.defineProperty(navigator, 'userAgent', {value: 'googlebot'});
  1994. }
  1995. };
  1996.  
  1997. scripts['4pda.ru'] = {
  1998. now: () => {
  1999. // https://greasyfork.org/en/scripts/14470-4pda-unbrender
  2000. let hStyle,
  2001. isForum = document.location.href.search('/forum/') !== -1,
  2002. remove = (node) => (node ? node.parentNode.removeChild(node) : null),
  2003. afterClean = () => remove(hStyle);
  2004.  
  2005. function beforeClean()
  2006. {
  2007. // attach styles before document displayed
  2008. hStyle = createStyle([
  2009. 'html { overflow-y: scroll }',
  2010. 'section[id] {'+(
  2011. 'position: absolute;'+
  2012. 'width: 100%'
  2013. )+'}',
  2014. 'article + aside * { display: none !important }',
  2015. '#header + div:after {'+(
  2016. 'content: "";'+
  2017. 'position: fixed;'+
  2018. 'top: 0;'+
  2019. 'left: 0;'+
  2020. 'width: 100%;'+
  2021. 'height: 100%;'+
  2022. 'background-color: #E6E7E9'
  2023. )+'}',
  2024. // http://codepen.io/Beaugust/pen/DByiE
  2025. '@keyframes spin { 100% { transform: rotate(360deg) } }',
  2026. 'article + aside:after {'+(
  2027. 'content: "";'+
  2028. 'position: absolute;'+
  2029. 'width: 150px;'+
  2030. 'height: 150px;'+
  2031. 'top: 150px;'+
  2032. 'left: 50%;'+
  2033. 'margin-top: -75px;'+
  2034. 'margin-left: -75px;'+
  2035. 'box-sizing: border-box;'+
  2036. 'border-radius: 100%;'+
  2037. 'border: 10px solid rgba(0, 0, 0, 0.2);'+
  2038. 'border-top-color: rgba(0, 0, 0, 0.6);'+
  2039. 'animation: spin 2s infinite linear'
  2040. )+'}'
  2041. ], {id:'ubrHider'}, true);
  2042.  
  2043. // display content of a page if time to load a page is more than 2 seconds to avoid
  2044. // blocking access to a page if it is loading for too long or stuck in a loading state
  2045. setTimeout(2000, afterClean);
  2046. }
  2047.  
  2048. createStyle([
  2049. '#nav .use-ad { display: block !important }',
  2050. 'article:not(.post) + article:not(#id),'+
  2051. 'html:not(#id)>body:not(#id) a[target="_blank"] img[height="90"] { display: none !important }'
  2052. ]);
  2053.  
  2054. if (!isForum)
  2055. beforeClean();
  2056.  
  2057. // save links to non-overridden functions to use later
  2058. let protectedElems;
  2059. // protect/hide changed attributes in case site attempt to restore them
  2060. function styleProtector(eventMode)
  2061. {
  2062. let _toLowerCase = String.prototype.toLowerCase,
  2063. isStyleText = (t) => (_toLowerCase.call(t) === 'style'),
  2064. protectedElems = new WeakMap();
  2065. function protoOverride(element, functionName, isStyleCheck, returnIfProtected)
  2066. {
  2067. let originalFunction = element.prototype[functionName];
  2068. element.prototype[functionName] = function wrapper()
  2069. {
  2070. if (protectedElems.has(this) && isStyleCheck(arguments[0]))
  2071. return returnIfProtected(this, arguments);
  2072. return originalFunction.apply(this, arguments);
  2073. };
  2074. }
  2075. protoOverride(Element, 'removeAttribute', isStyleText, () => undefined);
  2076. protoOverride(Element, 'hasAttribute', isStyleText, (_this) => protectedElems.get(_this) !== null);
  2077. protoOverride(Element, 'setAttribute', isStyleText, (_this, args) => protectedElems.set(_this, args[1]));
  2078. protoOverride(Element, 'getAttribute', isStyleText, (_this) => protectedElems.get(_this));
  2079. if (!eventMode)
  2080. return protectedElems;
  2081. else
  2082. {
  2083. let e = document.createEvent('Event');
  2084. e.initEvent('protoOverride', false, false);
  2085. window.protectedElems = protectedElems;
  2086. window.dispatchEvent(e);
  2087. }
  2088. }
  2089. if (!isFirefox)
  2090. protectedElems = styleProtector(false);
  2091. else
  2092. {
  2093. let script = document.createElement('script');
  2094. script.textContent = '(' + styleProtector.toString() + ')(true);';
  2095. window.addEventListener(
  2096. 'protoOverride', function protoOverrideCallback(e)
  2097. {
  2098. if (win.protectedElems) {
  2099. protectedElems = win.protectedElems;
  2100. delete win.protectedElems;
  2101. }
  2102. document.removeEventListener('protoOverride', protoOverrideCallback, true);
  2103. }, true
  2104. );
  2105. _appendChild(script);
  2106. _removeChild(script);
  2107. }
  2108.  
  2109. // clean a page
  2110. window.addEventListener(
  2111. 'DOMContentLoaded', function()
  2112. {
  2113. let width = () => window.innerWidth || _de.clientWidth || document.body.clientWidth || 0;
  2114. let height = () => window.innerHeight || _de.clientHeight || document.body.clientHeight || 0;
  2115.  
  2116. if (isForum)
  2117. {
  2118. let si = document.querySelector('#logostrip');
  2119. if (si)
  2120. remove(si.parentNode.nextSibling);
  2121. }
  2122.  
  2123. if (document.location.href.search('/forum/dl/') !== -1) {
  2124. document.body.setAttribute('style', (document.body.getAttribute('style')||'')+
  2125. ';background-color:black!important');
  2126. for (let itm of document.querySelectorAll('body>div'))
  2127. if (!itm.querySelector('.dw-fdwlink'))
  2128. remove(itm);
  2129. }
  2130.  
  2131. if (isForum) // Do not continue if it's a forum
  2132. return;
  2133.  
  2134. {
  2135. let si = document.querySelector('#header');
  2136. if (si)
  2137. {
  2138. let rem = si.previousSibling;
  2139. while (rem)
  2140. {
  2141. si = rem.previousSibling;
  2142. remove(rem);
  2143. rem = si;
  2144. }
  2145. }
  2146. }
  2147.  
  2148. for (let itm of document.querySelectorAll('#nav li[class]'))
  2149. if (itm && itm.querySelector('a[href^="/tag/"]'))
  2150. remove(itm);
  2151.  
  2152. let style, result,
  2153. fakeStyles = new WeakMap(),
  2154. styleProxy = {
  2155. get: function(target, prop)
  2156. {
  2157. let fakeStyle = fakeStyles.get(target);
  2158. return ((prop in fakeStyle) ? fakeStyle : target)[prop];
  2159. },
  2160. set: function(target, prop, value)
  2161. {
  2162. let fakeStyle = fakeStyles.get(target);
  2163. ((prop in fakeStyle) ? fakeStyle : target)[prop] = value;
  2164. return true;
  2165. }
  2166. };
  2167. for (let itm of document.querySelectorAll('DIV, A'))
  2168. {
  2169. if (itm.tagName ==='DIV' &&
  2170. itm.offsetWidth > 0.95 * width() &&
  2171. itm.offsetHeight > 0.85 * height())
  2172. {
  2173. style = window.getComputedStyle(itm, null);
  2174. result = [];
  2175.  
  2176. if (style.backgroundImage !== 'none')
  2177. result.push('background-image:none!important');
  2178.  
  2179. if (style.backgroundColor !== 'transparent' &&
  2180. style.backgroundColor !== 'rgba(0, 0, 0, 0)')
  2181. result.push('background-color:transparent!important');
  2182.  
  2183. if (result.length)
  2184. {
  2185. if (itm.getAttribute('style'))
  2186. result.unshift(itm.getAttribute('style'));
  2187.  
  2188. fakeStyles.set(itm.style, {
  2189. 'backgroundImage': itm.style.backgroundImage,
  2190. 'backgroundColor': itm.style.backgroundColor
  2191. });
  2192.  
  2193. try {
  2194. Object.defineProperty(itm, 'style', {
  2195. value: new Proxy(itm.style, styleProxy),
  2196. enumerable: true
  2197. });
  2198. } catch (e) {
  2199. console.log('Unable to protect style property.', e);
  2200. }
  2201.  
  2202. if (protectedElems)
  2203. protectedElems.set(itm, _getAttribute.call(itm, 'style'));
  2204.  
  2205. _setAttribute.call(itm, 'style', result.join(';'));
  2206. }
  2207. }
  2208. if (itm.tagName ==='A' &&
  2209. (itm.offsetWidth > 0.95 * width() ||
  2210. itm.offsetHeight > 0.85 * height()))
  2211. {
  2212. if (protectedElems)
  2213. protectedElems.set(itm, _getAttribute.call(itm, 'style'));
  2214.  
  2215. _setAttribute.call(itm, 'style', 'display:none!important');
  2216. }
  2217. }
  2218.  
  2219. for (let itm of document.querySelectorAll('ASIDE>DIV'))
  2220. if ( ((itm.querySelector('script, iframe, a[href*="/ad/www/"]') ||
  2221. itm.querySelector('img[src$=".gif"]:not([height="0"]), img[height="400"]')) &&
  2222. !itm.classList.contains('post') ) || !itm.childNodes.length )
  2223. remove(itm);
  2224.  
  2225. document.body.setAttribute('style', (document.body.getAttribute('style')||'')+';background-color:#E6E7E9!important');
  2226.  
  2227. // display content of the page
  2228. afterClean();
  2229. }
  2230. );
  2231. }
  2232. };
  2233.  
  2234. scripts['allmovie.pro'] = {
  2235. other: ['rufilmtv.org'],
  2236. dom: function()
  2237. {
  2238. // pretend to be Android to make site use different played for ads
  2239. if (isSafari)
  2240. return;
  2241. Object.defineProperty(navigator, 'userAgent', {
  2242. 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'; },
  2243. enumerable: true
  2244. });
  2245. }
  2246. };
  2247.  
  2248. scripts['anidub-online.ru'] = {
  2249. other: ['online.anidub.com'],
  2250. dom: function()
  2251. {
  2252. if (win.ogonekstart1)
  2253. win.ogonekstart1 = () => console.log("Fire in the hole!");
  2254. },
  2255. now: () => createStyle([
  2256. '.background {background: none!important;}',
  2257. '.background > script + div,'+
  2258. '.background > script ~ div:not([id]):not([class]) + div[id][class]'+
  2259. '{display:none!important}'
  2260. ])
  2261. };
  2262.  
  2263. scripts['drive2.ru'] = () => gardener('.c-block:not([data-metrika="recomm"]),.o-grid__item', />Реклама<\//i);
  2264.  
  2265. scripts['fishki.net'] = () => gardener('.drag_list > .drag_element, .list-view > .paddingtop15, .post-wrap', /543769|Новости\sпартнеров|Полезная\sреклама/);
  2266.  
  2267. scripts['gidonline.club'] = () => createStyle('.tray > div[style] {display: none!important}');
  2268.  
  2269. scripts['hdgo.cc'] = {
  2270. other: ['46.30.43.38', 'couber.be'],
  2271. now: () => (new MutationObserver(
  2272. function(ms)
  2273. {
  2274. let m, node;
  2275. for (m of ms) for (node of m.addedNodes)
  2276. if (node.tagName === 'SCRIPT' && _getAttribute.call(node, 'onerror') !== null)
  2277. node.removeAttribute('onerror');
  2278. }
  2279. )).observe(document.documentElement, { childList:true, subtree: true })
  2280. };
  2281.  
  2282. scripts['gismeteo.ru'] = {
  2283. other: ['gismeteo.ua'],
  2284. now: () => gardener('div > script', /AdvManager/i, { root: 'body', observe: true, parent: 'div'})
  2285. };
  2286.  
  2287. scripts['hdrezka.ag'] = () => {
  2288. Object.defineProperty(win, 'ab', { value: false, enumerable: true });
  2289. gardener('div[id][onclick][onmouseup][onmousedown]', /onmouseout/i);
  2290. };
  2291.  
  2292. scripts['imageban.ru'] = {
  2293. now: preventPopunders,
  2294. dom: () => win.addEventListener('unload', () => location.hash = 'x'+Math.random().toString(36).substr(2), true)
  2295. };
  2296.  
  2297. scripts['mail.ru'] = {
  2298. now: () => {
  2299. // Trick to prevent mail.ru from removing 3rd-party styles
  2300. scriptLander(
  2301. () => {
  2302. Object.defineProperty(Object.prototype, 'restoreVisibility', {
  2303. get: () => (() => null),
  2304. set: () => undefined
  2305. });
  2306.  
  2307. if (location.hostname !== 'e.mail.ru')
  2308. return;
  2309. let locator;
  2310. let fishnet = {
  2311. apply: (target, thisArg, args) => {
  2312. console.log(`locator.${target._name}(${JSON.stringify(args).slice(1,-1)})`);
  2313. return target.apply(thisArg, args);
  2314. }
  2315. };
  2316. Object.defineProperty(win, 'locator', {
  2317. set: function(l)
  2318. {
  2319. if ('setup' in l)
  2320. {
  2321. let _setup = l.setup;
  2322. l.setup = function(o)
  2323. {
  2324. for (let name in o)
  2325. switch(name) {
  2326. case 'enable':
  2327. o[name] = false;
  2328. console.log('Disable mimic mode.');
  2329. break;
  2330. case 'links':
  2331. o[name] = [];
  2332. console.log('Call with empty list of sheets.');
  2333. break;
  2334. default:
  2335. console.log(`Skipped unknown setup property '${name}'.`);
  2336. }
  2337. return _setup.call(this, o);
  2338. };
  2339. }
  2340. try {
  2341. for (let name in l)
  2342. if (l[name] instanceof Function) {
  2343. l[name]._name = name;
  2344. l[name] = new Proxy(l[name], fishnet);
  2345. console.log(`wrapped locator.${name}`);
  2346. }
  2347. } catch(e) {
  2348. console.log(e);
  2349. }
  2350. locator = l;
  2351. },
  2352. get: () => locator
  2353. });
  2354. }
  2355. );
  2356. }
  2357. };
  2358.  
  2359. scripts['megogo.net'] = {
  2360. now: () => {
  2361. let nt = new nullTools();
  2362. nt.define(win, 'adBlock', false);
  2363. nt.define(win, 'showAdBlockMessage', nt.func(null));
  2364. }
  2365. };
  2366.  
  2367. scripts['naruto-base.su'] = () => gardener('div[id^="entryID"],.block', /href="http.*?target="_blank"/i);
  2368.  
  2369. scripts['overclockers.ru'] = {
  2370. now: () => {
  2371. createStyle('.fixoldhtml {display:block!important}');
  2372. if (!isChrome && !isOpera)
  2373. return; // Looks like my code works only in Chrome-like browsers
  2374. let noContentYet = true;
  2375. function jWrap()
  2376. {
  2377. win.$ = new Proxy(
  2378. win.$, {
  2379. apply: function(_$, _this, args)
  2380. {
  2381. let _ret = _$.apply(_this, args);
  2382. if (_ret[0] === document.body)
  2383. _ret.html = () => console.log('Anti-adblock prevented.');
  2384. return _ret;
  2385. }
  2386. }
  2387. );
  2388. win.jQuery = win.$;
  2389. }
  2390. (function jReady()
  2391. {
  2392. if (!win.$ && noContentYet)
  2393. setTimeout(jReady, 0);
  2394. else
  2395. jWrap();
  2396. })();
  2397. document.addEventListener ('DOMContentLoaded', () => (noContentYet = false), false);
  2398. }
  2399. };
  2400. scripts['forums.overclockers.ru'] = {
  2401. now: () => {
  2402. createStyle('.needblock {position: fixed; left: -10000px}');
  2403. Object.defineProperty(win, 'adblck', {
  2404. get: () => 'no',
  2405. set: () => undefined,
  2406. enumerable: true
  2407. });
  2408. }
  2409. };
  2410.  
  2411. scripts['pb.wtf'] = {
  2412. other: ['piratbit.org', 'piratbit.ru'],
  2413. now: () => {
  2414. // line above topic content and images in the slider in the header
  2415. gardener(
  2416. 'a[href^="/exit/"], a[href^="/fxt/"], a[href$="=="]',
  2417. /img|Реклама|center/i,
  2418. { root: '.release-navbar,#page_content', observe: true, parent: 'div,tr' }
  2419. );
  2420. // ads in comments
  2421. gardener('img[data-name="PiraBo"]', /./i, {root:'#main_content .table', observe:true, parent:'tr'});
  2422. }
  2423. };
  2424.  
  2425. scripts['pikabu.ru'] = () => gardener('.story', /story__sponsor|story__gag|profile\/ads"/i, {root: '.inner_wrap', observe: true});
  2426.  
  2427. scripts['qrz.ru'] = {
  2428. now: () => {
  2429. let nt = new nullTools();
  2430. nt.define(win, 'ab', false);
  2431. nt.define(win, 'tryMessage', nt.func(null));
  2432. }
  2433. };
  2434.  
  2435. scripts['razlozhi.ru'] = {
  2436. now: () => {
  2437. for (let func of ['createShadowRoot', 'attachShadow'])
  2438. if (func in Element.prototype)
  2439. Element.prototype[func] = function(){ return this.cloneNode(); };
  2440. }
  2441. };
  2442.  
  2443. scripts['rbc.ru'] = {
  2444. dom: () => {
  2445. let _preventDefault = Event.prototype.preventDefault;
  2446. Event.prototype.preventDefault = function preventDefault()
  2447. {
  2448. let t = this.target;
  2449. if (t instanceof HTMLAnchorElement || t.closest('A'))
  2450. throw new Error('an.yandex redirect prevention');
  2451. return _preventDefault.call(this);
  2452. };
  2453.  
  2454. function cleaner(nodes)
  2455. {
  2456. for (let node of nodes)
  2457. {
  2458. if (!node.classList || !node.classList.contains('js-yandex-counter'))
  2459. continue;
  2460. node.classList.remove('js-yandex-counter');
  2461. node.removeAttribute('data-yandex-name');
  2462. node.removeAttribute('data-yandex-params');
  2463. }
  2464. }
  2465. cleaner(_de.querySelectorAll('.js-yandex-counter'));
  2466.  
  2467. (new MutationObserver(
  2468. ms => { for (let m of ms) cleaner(m.addedNodes); }
  2469. )).observe(_de, {childList: true, subtree: true});
  2470. }
  2471. };
  2472.  
  2473. scripts['rp5.ru'] = {
  2474. other: ['rp5.by', 'rp5.kz', 'rp5.ua'],
  2475. dom: () => {
  2476. createStyle('#bannerBottom {display: none!important}');
  2477. let co = document.querySelector('#content');
  2478. if (!co)
  2479. return;
  2480. let nodes = co.children;
  2481. let i = nodes.length;
  2482. while(i--)
  2483. if (nodes[i].querySelector('a[href*="?AdvertMgmt="]'))
  2484. nodes[i].parentNode.removeChild(nodes[i]);
  2485. nodes = co.parentNode.children;
  2486. i = nodes.length;
  2487. while(i--)
  2488. if (nodes[i] !== co)
  2489. nodes[i].parentNode.removeChild(nodes[i]);
  2490. nodes = co.childNodes;
  2491. }
  2492. };
  2493.  
  2494. scripts['rustorka.com'] = {
  2495. other: ['rumedia.ws'],
  2496. now: () => {
  2497. createStyle('.header > div:not(.head-block) a, #sidebar1 img, #logo img {opacity:0!important}', {
  2498. id: 'tempHidingStyles'
  2499. }, true);
  2500. preventPopups();
  2501. },
  2502. dom: () => {
  2503. for (let o of document.querySelectorAll('IMG, A'))
  2504. if ((o.clientWidth === 728 && o.clientHeight === 90) ||
  2505. (o.clientWidth === 300 && o.clientHeight === 250))
  2506. {
  2507. while (o && o.tagName !== 'A')
  2508. o = o.parentNode;
  2509. if (o)
  2510. _setAttribute.call(o, 'style', 'display: none !important');
  2511. }
  2512. let s = document.querySelector('#tempHidingStyles');
  2513. s.parentNode.removeChild(s);
  2514. }
  2515. };
  2516.  
  2517. scripts['sport-express.ru'] = () => gardener('.js-relap__item',/>Реклама\s+<\//, {root:'.container', observe: true});
  2518.  
  2519. scripts['sports.ru'] = {
  2520. now: () => {
  2521. gardener('.aside-news-list__item', /aside-news-list__advert/i, {root:'.columns-layout__left', observe: true});
  2522. gardener('.material-list__item', /Реклама/i, {root:'.columns-layout', observe: true});
  2523. // extra functionality: shows/hides panel at the top depending on scroll direction
  2524. createStyle([
  2525. '.user-panel__fixed { transition: top 0.2s ease-in-out!important; }',
  2526. '.user-panel-up { top: -40px!important }'
  2527. ], {id: 'userPanelSlide'}, false);
  2528. },
  2529. dom: () => {
  2530. (function lookForPanel()
  2531. {
  2532. let panel = document.querySelector('.user-panel__fixed');
  2533. if (!panel)
  2534. setTimeout(lookForPanel, 100);
  2535. else
  2536. window.addEventListener(
  2537. 'wheel', function(e)
  2538. {
  2539. if (e.deltaY > 0 && !panel.classList.contains('user-panel-up'))
  2540. panel.classList.add('user-panel-up');
  2541. else if (e.deltaY < 0 && panel.classList.contains('user-panel-up'))
  2542. panel.classList.remove('user-panel-up');
  2543. }, false
  2544. );
  2545. })();
  2546. }
  2547. };
  2548.  
  2549. scripts['vk.com'] = () => gardener((
  2550. '#wk_content > #wl_post > div,'+
  2551. '#page_wall_posts > div[id^="post-"],'+
  2552. 'div[class^="feed_row "] > div[id^="post-"],'+
  2553. 'div[class^="feed_row "] > div[id^="feed_repost-"]'
  2554. ), /wall_marked_as_ads/, {root: 'body', observe: true});
  2555.  
  2556. scripts['yap.ru'] = {
  2557. other: ['yaplakal.com'],
  2558. now: () => {
  2559. gardener('form > table[id^="p_row_"]:nth-of-type(2)', /member1438|Administration/);
  2560. gardener('.icon-comments', /member1438|Administration|\/go\/\?http/, {parent:'tr', siblings:-2});
  2561. }
  2562. };
  2563.  
  2564. scripts['rambler.ru'] = {
  2565. other: ['championat.com','gazeta.ru','media.eagleplatform.com','lenta.ru'],
  2566. now: () => scriptLander(
  2567. () => {
  2568. if (location.hostname.endsWith('.media.eagleplatform.com'))
  2569. return;
  2570. let _cssText = Object.getOwnPropertyDescriptor(CSSRule.prototype, 'cssText');
  2571. let _cssText_get = _cssText.get;
  2572. _cssText.configurable = false;
  2573. _cssText.get = function()
  2574. {
  2575. let cssText = _cssText_get.call(this);
  2576. if (cssText.includes('content:'))
  2577. {
  2578. console.log('Blocked access to suspicious cssText:', cssText.slice(0,60), '\u2026', cssText.length);
  2579. return null;
  2580. }
  2581. return cssText;
  2582. };
  2583. Object.defineProperty(CSSRule.prototype, 'cssText', _cssText);
  2584. // fake global Adf object
  2585. let nt = new nullTools();
  2586. nt.define(win, 'Adf', nt.proxy({
  2587. banner: nt.proxy({
  2588. sspScroll: nt.func(),
  2589. ssp: nt.func()
  2590. })
  2591. }));
  2592. // extra script to remove partner news on gazeta.ru
  2593. if (!location.hostname.includes('gazeta.ru'))
  2594. return;
  2595. (new MutationObserver(
  2596. (ms) => {
  2597. let m, node, header;
  2598. for (m of ms) for (node of m.addedNodes)
  2599. if (node instanceof HTMLDivElement && node.matches('.sausage'))
  2600. {
  2601. header = node.querySelector('.sausage-header');
  2602. if (header && /новости\s+партн[её]ров/i.test(header.textContent))
  2603. node.style.display = 'none';
  2604. }
  2605. }
  2606. )).observe(document.documentElement, { childList:true, subtree: true });
  2607. }, nullTools
  2608. ),
  2609. dom: () => {
  2610. // extra script to block video autoplay on Rambler domains
  2611. function unstopper(e, stopper, timeout)
  2612. {
  2613. if (timeout)
  2614. clearTimeout(timeout);
  2615. return setTimeout(
  2616. (e) => e.target.removeEventListener('playing', stopper, false),
  2617. 333, e
  2618. );
  2619. }
  2620. function stopper(e)
  2621. {
  2622. let timeout = unstopper(e, stopper);
  2623. e.target.addEventListener(
  2624. 'pause', function()
  2625. {
  2626. timeout = unstopper(e, stopper, timeout);
  2627. }, false
  2628. );
  2629. let btn = document.querySelector('.eplayer-skin-toggle-playing');
  2630. if (btn)
  2631. btn.click();
  2632. else
  2633. e.target.pause();
  2634. }
  2635. let observer = (new MutationObserver(
  2636. (ms) => {
  2637. for (let m of ms)
  2638. if (!m.target.appliedStopper)
  2639. {
  2640. m.target.appliedStopper = true;
  2641. m.target.addEventListener('playing', stopper, false);
  2642. }
  2643. }
  2644. ));
  2645. observer.observe(document.documentElement, { subtree: true, attributes: true, attributeFilter: ['autoplay'] });
  2646. }
  2647. };
  2648.  
  2649. scripts['reactor.cc'] = {
  2650. other: ['joyreactor.cc', 'pornreactor.cc'],
  2651. now: () => win.open = (function(){ throw new Error('Redirect prevention.'); }).bind(window),
  2652. click: function(e)
  2653. {
  2654. let node = e.target;
  2655. if (node.nodeType === Node.ELEMENT_NODE &&
  2656. node.style.position === 'absolute' &&
  2657. node.style.zIndex > 0)
  2658. node.parentNode.removeChild(node);
  2659. },
  2660. dom: function()
  2661. {
  2662. let words = new RegExp(
  2663. 'блокировщика рекламы'
  2664. .split('')
  2665. .map(function(e){return e+'[\u200b\u200c\u200d]*';})
  2666. .join('')
  2667. .replace(' ', '\\s*')
  2668. .replace(/[аоре]/g, function(e){return ['[аa]','[оo]','[рp]','[еe]']['аоре'.indexOf(e)];}),
  2669. 'i'),
  2670. can;
  2671. function deeper(spider)
  2672. {
  2673. let c, l, n;
  2674. if (words.test(spider.innerText))
  2675. {
  2676. if (spider.nodeType === Node.TEXT_NODE)
  2677. return true;
  2678. c = spider.childNodes;
  2679. l = c.length;
  2680. n = 0;
  2681. while(l--)
  2682. if (deeper(c[l]), can)
  2683. n++;
  2684. if (n > 0 && n === c.length && spider.offsetHeight < 750)
  2685. can.push(spider);
  2686. return false;
  2687. }
  2688. return true;
  2689. }
  2690. function probe()
  2691. {
  2692. if (words.test(document.body.innerText))
  2693. {
  2694. can = [];
  2695. deeper(document.body);
  2696. let i = can.length, spider;
  2697. while(i--) {
  2698. spider = can[i];
  2699. if (spider.offsetHeight > 10 && spider.offsetHeight < 750)
  2700. _setAttribute.call(spider, 'style', 'background:none!important');
  2701. }
  2702. }
  2703. }
  2704. (new MutationObserver(probe))
  2705. .observe(document, { childList:true, subtree:true });
  2706. }
  2707. };
  2708.  
  2709. scripts['auto.ru'] = () => {
  2710. let words = /Реклама|Яндекс.Директ|yandex_ad_/;
  2711. let userAdsListAds = (
  2712. '.listing-list > .listing-item,'+
  2713. '.listing-item_type_fixed.listing-item'
  2714. );
  2715. let catalogAds = (
  2716. 'div[class*="layout_catalog-inline"],'+
  2717. 'div[class$="layout_horizontal"]'
  2718. );
  2719. let otherAds = (
  2720. '.advt_auto,'+
  2721. '.sidebar-block,'+
  2722. '.pager-listing + div[class],'+
  2723. '.card > div[class][style],'+
  2724. '.sidebar > div[class],'+
  2725. '.main-page__section + div[class],'+
  2726. '.listing > tbody'
  2727. );
  2728. gardener(userAdsListAds, words, {root:'.listing-wrap', observe:true});
  2729. gardener(catalogAds, words, {root:'.catalog__page,.content__wrapper', observe:true});
  2730. gardener(otherAds, words);
  2731. };
  2732.  
  2733. scripts['rsload.net'] = {
  2734. load: () => {
  2735. let dis = document.querySelector('label[class*="cb-disable"]');
  2736. if (dis)
  2737. dis.click();
  2738. },
  2739. click: () => {
  2740. let t = e.target;
  2741. if (t && t.href && (/:\/\/\d+\.\d+\.\d+\.\d+\//.test(t.href)))
  2742. t.href = t.href.replace('://','://rsload.net:rsload.net@');
  2743. }
  2744. };
  2745.  
  2746. let domain, name;
  2747. // add alternative domain names if present and wrap functions into objects
  2748. for (name in scripts)
  2749. {
  2750. if (scripts[name] instanceof Function)
  2751. scripts[name] = { now: scripts[name] };
  2752. for (domain of (scripts[name].other||[]))
  2753. {
  2754. if (domain in scripts)
  2755. console.log('Error in scripts list. Script for', name, 'replaced script for', domain);
  2756. scripts[domain] = scripts[name];
  2757. }
  2758. delete scripts[name].other;
  2759. }
  2760. // look for current domain in the list and run appropriate code
  2761. domain = document.domain;
  2762. while (domain.indexOf('.') > -1)
  2763. {
  2764. if (domain in scripts) for (name in scripts[domain])
  2765. switch(name)
  2766. {
  2767. case 'now':
  2768. scripts[domain][name]();
  2769. break;
  2770. case 'load':
  2771. window.addEventListener('load', scripts[domain][name], false);
  2772. break;
  2773. case 'dom':
  2774. document.addEventListener('DOMContentLoaded', scripts[domain][name], false);
  2775. break;
  2776. default:
  2777. document.addEventListener (name, scripts[domain][name], false);
  2778. }
  2779. domain = domain.slice(domain.indexOf('.') + 1);
  2780. }
  2781. })();