RU AdList JS Fixes

try to take over the world!

当前为 2017-12-19 提交的版本,查看 最新版本

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