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