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.3
  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', 'clickmap'])
  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. let nt = new nullTools({log: false});
  1553. let AwapsJsonAPI_Json = nt.proxy({
  1554. prototype: nt.proxy({
  1555. setID: nt.proxy(nt.func(null, 'setID')),
  1556. checkBannerVisibility: nt.proxy(nt.func(true, 'checkBannerVisibility')),
  1557. addIframeContent: nt.proxy(function(...args) {
  1558. try {
  1559. let frame = args[1][0].parentNode;
  1560. frame.parentNode.removeChild(frame);
  1561. console.log(`Removed banner placeholder.`);
  1562. } catch(ignore) {
  1563. console.log(`Can't locate frame object to remove.`);
  1564. }
  1565. }),
  1566. addImageContent: nt.proxy(nt.func(null, 'addImageContent')),
  1567. sendCounts: nt.proxy(nt.func(null, 'sendCounts')),
  1568. getHTML: nt.proxy(nt.func('', 'getHTML')),
  1569. expand: nt.proxy(nt.func(null, 'expand'))
  1570. })
  1571. });
  1572. if ('AwapsJsonAPI' in win) {
  1573. console.log('Oops! AwapsJsonAPI already defined.');
  1574. win.AwapsJsonAPI.Json = AwapsJsonAPI_Json;
  1575. } else {
  1576. nt.define(win, 'AwapsJsonAPI', nt.proxy({
  1577. Json: AwapsJsonAPI_Json
  1578. }));
  1579. }
  1580.  
  1581. let home = win.home || {};
  1582. function parseExport(x) {
  1583. if (!x)
  1584. return x;
  1585. // remove banner placeholder
  1586. if (x.banner && x.banner.cls) {
  1587. let banners = document.querySelectorAll('.' + x.banner.cls.banner__parent);
  1588. for (let banner of banners) {
  1589. _setAttribute.call(banner, 'style', 'display:none!important');
  1590. console.log('Hid banner placeholder.');
  1591. }
  1592. }
  1593.  
  1594. // remove banner data and some other stuff
  1595. delete x.banner;
  1596. delete x.consistency;
  1597. delete x['i-bannerid'];
  1598. delete x['i-counter'];
  1599. delete x['ga-counter'];
  1600. delete x['promo-curtain'];
  1601.  
  1602. return x;
  1603. };
  1604. let home_export = parseExport(home.export);
  1605. Object.defineProperty(home, 'export', {
  1606. get: x => home_export,
  1607. set: x => {
  1608. home_export = parseExport(x);
  1609. }
  1610. });
  1611. nt.define(win, 'home', home);
  1612.  
  1613. if ('attachShadow' in Element.prototype) {
  1614. let fakeRoot = () => ({
  1615. firstChild: null,
  1616. appendChild: ()=>null,
  1617. querySelector: ()=>null,
  1618. querySelectorAll: ()=>null
  1619. });
  1620. Element.prototype.createShadowRoot = fakeRoot;
  1621. let shadows = new WeakMap();
  1622. let _attachShadow = Object.getOwnPropertyDescriptor(Element.prototype, 'attachShadow');
  1623. let _call_attachShadow = _attachShadow.value;
  1624. _attachShadow.value = function() {
  1625. return shadows.set(this, fakeRoot()).get(this);
  1626. };
  1627. Object.defineProperty(Element.prototype, 'attachShadow', _attachShadow);
  1628. let _shadowRoot = Object.getOwnPropertyDescriptor(Element.prototype, 'shadowRoot');
  1629. _shadowRoot.set = () => null;
  1630. _shadowRoot.get = function() {
  1631. return shadows.has(this) ? shadows.get(this) : void 0;
  1632. };
  1633. Object.defineProperty(Element.prototype, 'shadowRoot', _shadowRoot);
  1634. }
  1635. // Partially based on https://greasyfork.org/en/scripts/22737-remove-yandex-redirect
  1636. let selectors = (
  1637. 'A[onmousedown*="/jsredir"],'+
  1638. 'A[data-vdir-href],'+
  1639. 'A[data-counter]'
  1640. );
  1641. let removeTrackingAttributes = function(link)
  1642. {
  1643. link.removeAttribute('onmousedown');
  1644. if (link.hasAttribute('data-vdir-href')) {
  1645. link.removeAttribute('data-vdir-href');
  1646. link.removeAttribute('data-orig-href');
  1647. }
  1648. if (link.hasAttribute('data-counter')) {
  1649. link.removeAttribute('data-counter');
  1650. link.removeAttribute('data-bem');
  1651. }
  1652. };
  1653. let removeTracking = function(scope)
  1654. {
  1655. for (let link of scope.querySelectorAll(selectors))
  1656. removeTrackingAttributes(link);
  1657. };
  1658. document.addEventListener('DOMContentLoaded', (e) => removeTracking(e.target));
  1659. (new MutationObserver(
  1660. function(ms)
  1661. {
  1662. let m, node;
  1663. for (m of ms) for (node of m.addedNodes) if (node.nodeType === Node.ELEMENT_NODE)
  1664. if (node.tagName === 'A' && node.matches(selectors)) {
  1665. removeTrackingAttributes(node);
  1666. } else {
  1667. removeTracking(node);
  1668. }
  1669. }
  1670. )).observe(_de, { childList: true, subtree: true });
  1671.  
  1672. //skip fixes for other sites
  1673. return;
  1674. }
  1675.  
  1676. // https://greasyfork.org/en/scripts/21937-moonwalk-hdgo-kodik-fix v0.8 (adapted)
  1677. document.addEventListener(
  1678. 'DOMContentLoaded', function()
  1679. {//createPlayer();
  1680. function log (name) {
  1681. console.log(`Player FIX: Detected ${name} player on ${location.href}`);
  1682. }
  1683. if (win.adv_enabled !== undefined && win.condition_detected !== undefined)
  1684. {
  1685. log('Moonwalk');
  1686. if (win.adv_enabled)
  1687. win.adv_enabled = false;
  1688. win.condition_detected = false;
  1689. if (win.MXoverrollCallback)
  1690. document.addEventListener(
  1691. 'click', function catcher(e)
  1692. {
  1693. e.stopPropagation();
  1694. win.MXoverrollCallback.call(window);
  1695. document.removeEventListener('click', catcher, true);
  1696. }, true
  1697. );
  1698. }
  1699. else if (win.stat_url !== undefined && win.is_html5 !== undefined && win.is_wp8 !== undefined)
  1700. {
  1701. log('HDGo');
  1702. document.body.onclick = null;
  1703. let tmp = document.querySelector('#swtf');
  1704. if (tmp)
  1705. tmp.style.display = 'none';
  1706. if (win.banner_second !== undefined)
  1707. win.banner_second = 0;
  1708. if (win.$banner_ads !== undefined)
  1709. win.$banner_ads = false;
  1710. if (win.$new_ads !== undefined)
  1711. win.$new_ads = false;
  1712. if (win.createCookie !== undefined)
  1713. win.createCookie('popup', 'true', '999');
  1714. if (win.canRunAds !== undefined && win.canRunAds !== true)
  1715. win.canRunAds = true;
  1716. }
  1717. else if (win.MXoverrollCallback && win.iframeSearch !== undefined)
  1718. {
  1719. log('Kodik');
  1720. let tmp = document.querySelector('.play_button');
  1721. if (tmp)
  1722. tmp.onclick = win.MXoverrollCallback.bind(window);
  1723. win.IsAdBlock = false;
  1724. }
  1725. else if (win.getnextepisode && win.uppodEvent)
  1726. {
  1727. log('Share-Serials.net');
  1728. scriptLander(
  1729. function()
  1730. {
  1731. let _setInterval = win.setInterval,
  1732. _setTimeout = win.setTimeout;
  1733. win.setInterval = function(func)
  1734. {
  1735. if (func instanceof Function && func.toString().indexOf('_delay') > -1)
  1736. {
  1737. let intv = _setInterval.call(
  1738. this, function()
  1739. {
  1740. _setTimeout.call(
  1741. this, function(intv)
  1742. {
  1743. clearInterval(intv);
  1744. let timer = document.querySelector('#timer');
  1745. if (timer)
  1746. timer.click();
  1747. }, 100, intv);
  1748. func.call(this);
  1749. }, 5
  1750. );
  1751.  
  1752. return intv;
  1753. }
  1754. return _setInterval.apply(this, arguments);
  1755. };
  1756. win.setTimeout = function(func) {
  1757. if (func instanceof Function && func.toString().indexOf('adv_showed') > -1)
  1758. {
  1759. return _setTimeout.call(this, func, 0);
  1760. }
  1761. return _setTimeout.apply(this, arguments);
  1762. };
  1763. }
  1764. );
  1765. } else if ('ADC' in win)
  1766. {
  1767. log('vjs-creatives plugin in');
  1768. let replacer = (obj) => {
  1769. for (let name in obj)
  1770. if (obj[name] instanceof Function)
  1771. obj[name] = () => null;
  1772. };
  1773. replacer(win.ADC);
  1774. replacer(win.currentAdSlot);
  1775. }
  1776. }, false
  1777. );
  1778.  
  1779. // piguiqproxy.com circumvention prevention
  1780. scriptLander(
  1781. function()
  1782. {
  1783. let _open = XMLHttpRequest.prototype.open;
  1784. let blacklist = /[/.@](piguiqproxy\.com|rcdn\.pro)[:/]/i;
  1785. XMLHttpRequest.prototype.open = function(method, url)
  1786. {
  1787. if (method === 'GET' && blacklist.test(url))
  1788. {
  1789. this.send = () => null;
  1790. this.setRequestHeader = () => null;
  1791. console.log('Blocked request: ', url);
  1792. return;
  1793. }
  1794. return _open.apply(this, arguments);
  1795. };
  1796. }
  1797. );
  1798.  
  1799. // === Helper functions ===
  1800.  
  1801. // function to search and remove nodes by content
  1802. // selector - standard CSS selector to define set of nodes to check
  1803. // words - regular expression to check content of the suspicious nodes
  1804. // params - object with multiple extra parameters:
  1805. // .log - display log in the console
  1806. // .hide - set display to none instead of removing from the page
  1807. // .parent - parent node to remove if content is found in the child node
  1808. // .siblings - number of simling nodes to remove (excluding text nodes)
  1809. let scRemove = (node) => node.parentNode.removeChild(node);
  1810. let scHide = function(node)
  1811. {
  1812. let style = _getAttribute.call(node, 'style') || '',
  1813. hide = ';display:none!important;';
  1814. if (style.indexOf(hide) < 0)
  1815. _setAttribute.call(node, 'style', style + hide);
  1816. };
  1817.  
  1818. function scissors (selector, words, scope, params)
  1819. {
  1820. let logger = function() { return params.log ? console.log(...arguments) : null; };
  1821. if (!scope.contains(document.body))
  1822. logger('[s] scope', scope);
  1823. let remFunc = (params.hide ? scHide : scRemove),
  1824. iterFunc = (params.siblings > 0 ? 'nextElementSibling' : 'previousElementSibling'),
  1825. toRemove = [],
  1826. siblings;
  1827. for (let node of scope.querySelectorAll(selector))
  1828. {
  1829. // drill up to a parent node if specified, break if not found
  1830. if (params.parent)
  1831. {
  1832. let old = node;
  1833. node = node.closest(params.parent);
  1834. if (node === null || node.contains(scope))
  1835. {
  1836. logger('[s] went out of scope with', old);
  1837. continue;
  1838. }
  1839. }
  1840. logger('[s] processing', node);
  1841. if (toRemove.includes(node))
  1842. continue;
  1843. if (words.test(node.innerHTML))
  1844. {
  1845. // skip node if already marked for removal
  1846. logger('[s] marked for removal');
  1847. toRemove.push(node);
  1848. // add multiple nodes if defined more than one sibling
  1849. siblings = Math.abs(params.siblings) || 0;
  1850. while (siblings)
  1851. {
  1852. node = node[iterFunc];
  1853. if (!node) break; // can't go any further - exit
  1854. logger('[s] adding sibling node', node);
  1855. toRemove.push(node);
  1856. siblings -= 1;
  1857. }
  1858. }
  1859. }
  1860. let toSkip = [];
  1861. for (let node of toRemove)
  1862. if (!toRemove.every(other => other === node || !node.contains(other)))
  1863. toSkip.push(node);
  1864. if (toRemove.length)
  1865. logger(`[s] proceeding with ${params.hide?'hide':'removal'} of`, toRemove, `skip`, toSkip);
  1866. for (let node of toRemove) if (!toSkip.includes(node))
  1867. remFunc(node);
  1868. }
  1869.  
  1870. // function to perform multiple checks if ads inserted with a delay
  1871. // by default does 30 checks withing a 3 seconds unless nonstop mode specified
  1872. // also does 1 extra check when a page completely loads
  1873. // selector and words - passed dow to scissors
  1874. // params - object with multiple extra parameters:
  1875. // .log - display log in the console
  1876. // .root - selector to narrow down scope to scan;
  1877. // .observe - if true then check will be performed continuously;
  1878. // Other parameters passed down to scissors.
  1879. function gardener(selector, words, params)
  1880. {
  1881. let logger = function() { return params.log ? console.log(...arguments) : null; };
  1882. params = params || {};
  1883. logger(`[gardener] selector: '${selector}' detector: ${words} options: ${JSON.stringify(params)}`);
  1884. let scope;
  1885. let globalScope = [_de];
  1886. let domLoaded = false;
  1887. let getScope = root => root ? _de.querySelectorAll(root) : globalScope;
  1888. let onevent = e => {
  1889. logger(`[gardener] cleanup on ${Object.getPrototypeOf(e)} "${e.type}"`);
  1890. for (let node of scope)
  1891. scissors(selector, words, node, params);
  1892. };
  1893. let repeater = n => {
  1894. if (!domLoaded && n) {
  1895. setTimeout(repeater, 500, n - 1);
  1896. scope = getScope(params.root);
  1897. if (!scope) // exit if the root element is not present on the page
  1898. return 0;
  1899. onevent({type: 'Repeater'});
  1900. }
  1901. };
  1902. repeater(20);
  1903. document.addEventListener(
  1904. 'DOMContentLoaded', (e) => {
  1905. domLoaded = true;
  1906. // narrow down scope to a specific element
  1907. scope = getScope(params.root);
  1908. if (!scope) // exit if the root element is not present on the page
  1909. return 0;
  1910. logger('[g] scope', scope);
  1911. // add observe mode if required
  1912. if (params.observe)
  1913. {
  1914. let params = { childList:true, subtree: true };
  1915. let observer = new MutationObserver(
  1916. function(ms)
  1917. {
  1918. for (let m of ms)
  1919. if (m.addedNodes.length)
  1920. onevent(m);
  1921. }
  1922. );
  1923. for (let node of scope)
  1924. observer.observe(node, params);
  1925. logger('[g] observer enabled');
  1926. }
  1927. onevent(e);
  1928. }, false);
  1929. // wait for a full page load to do one extra cut
  1930. win.addEventListener('load', onevent, false);
  1931. }
  1932.  
  1933. // wrap popular methods to open a new tab to catch specific behaviours
  1934. function createWindowOpenWrapper(openFunc, onClickFunc)
  1935. {
  1936. let _createElement = Document.prototype.createElement,
  1937. _appendChild = Element.prototype.appendChild,
  1938. fakeNative = (f) => (f.toString = () => `function ${f.name}() { [native code] }`);
  1939.  
  1940. let nt = new nullTools();
  1941. fakeNative(openFunc);
  1942.  
  1943. let parser = _createElement.call(document, 'a');
  1944. let openWhitelist = (url) => {
  1945. parser.href = url;
  1946. return parser.hostname === 'rustorka.com' && parser.pathname === '/forum/posting.php'&& parser.search.startsWith('?mode=') ||
  1947. parser.hostname === 'www.imdb.com' || parser.hostname === 'www.kinopoisk.ru';
  1948. };
  1949.  
  1950. let redefineOpen = (obj) => {
  1951. for (let root of [obj, obj.document, obj.Document.prototype]) if ('open' in root) {
  1952. let _open = root.open.bind(root);
  1953. nt.define(root, 'open', (...args) => {
  1954. if (openWhitelist(args[0])) {
  1955. console.log('Whitelisted popup:', ...args);
  1956. return _open(...args);
  1957. }
  1958. return openFunc(...args);
  1959. });
  1960. }
  1961. };
  1962. redefineOpen(win);
  1963.  
  1964. function createElement(name) {
  1965. '[native code]';
  1966. // jshint validthis:true
  1967. let el = _createElement.apply(this, arguments);
  1968. // click-dispatch check for Google Chrome and similar browsers
  1969. if (el instanceof HTMLAnchorElement)
  1970. el.addEventListener('click', onClickFunc, false);
  1971. // redefine window.open in first-party frames
  1972. if (el instanceof HTMLIFrameElement || el instanceof HTMLObjectElement)
  1973. el.addEventListener('load', (e) => {
  1974. try {
  1975. redefineOpen(e.target.contentWindow);
  1976. } catch(ignore) {}
  1977. }, false);
  1978. return el;
  1979. }
  1980. fakeNative(createElement);
  1981.  
  1982. let redefineCreateElement = (obj) => {
  1983. for (let root of [obj.document, obj.Document.prototype]) if ('createElement' in root)
  1984. nt.define(root, 'createElement', createElement);
  1985. };
  1986. redefineCreateElement(win);
  1987.  
  1988. // wrap window.open in newly added first-party frames
  1989. Element.prototype.appendChild = function appendChild()
  1990. {
  1991. '[native code]';
  1992. let el = _appendChild.apply(this, arguments);
  1993. if (el instanceof HTMLIFrameElement) {
  1994. try {
  1995. redefineOpen(el.contentWindow);
  1996. redefineCreateElement(el.contentWindow);
  1997. } catch(ignore) {}
  1998. }
  1999. return el;
  2000. };
  2001. fakeNative(Element.prototype.appendChild);
  2002. }
  2003.  
  2004. // Function to catch and block various methods to open a new window with 3rd-party content.
  2005. // Some advertisement networks went way past simple window.open call to circumvent default popup protection.
  2006. // This funciton blocks window.open, ability to restore original window.open from an IFRAME object,
  2007. // ability to perform an untrusted (not initiated by user) click on a link, click on a link without a parent
  2008. // node or simply a link with piece of javascript code in the HREF attribute.
  2009. function preventPopups()
  2010. {
  2011. // whitelist
  2012. if (!(location.hostname === 'rustorka.com' && location.pathname === '/forum/shoutbox.php')) {
  2013. // call sandbox-me if in iframe and not whitelisted
  2014. if (inIFrame) {
  2015. win.top.postMessage({ name: 'sandbox-me', href: win.location.href }, '*');
  2016. return;
  2017. }
  2018. }
  2019.  
  2020.  
  2021. scriptLander(() => {
  2022. let open = (...args) => {
  2023. '[native code]';
  2024. console.warn('Site attempted to open a new window', args);
  2025. if (new RegExp(`^https?://${location.hostname}/`).test(args[0])) // skip extra click in case of blocked popunder
  2026. location.assign(args[0]);
  2027. return {
  2028. document: {
  2029. write: () => {},
  2030. writeln: () => {}
  2031. }
  2032. };
  2033. };
  2034.  
  2035. let clickHandler = (e) => {
  2036. let link = e.target;
  2037. if (!link.parentNode || !e.isTrusted ||
  2038. (link.href && link.href.trim().toLowerCase().indexOf('javascript') === 0))
  2039. {
  2040. e.preventDefault();
  2041. console.warn('Blocked suspicious click event', e, 'on', e.target);
  2042. }
  2043. };
  2044.  
  2045. createWindowOpenWrapper(open, clickHandler);
  2046.  
  2047. console.log('Popup prevention enabled.');
  2048. }, nullTools, createWindowOpenWrapper);
  2049. }
  2050.  
  2051. // Helper function to close background tab if site opens itself in a new tab and then
  2052. // loads a 3rd-party page in the background one (thus performing background redirect).
  2053. function preventPopunders()
  2054. {
  2055. // create "close_me" event to call high-level window.close()
  2056. let eventName = `close_me_${Math.random().toString(36).substr(2)}`;
  2057. let callClose = () => (console.log('close call'), window.close());
  2058. window.addEventListener(eventName, callClose, true);
  2059.  
  2060. scriptLander(() => {
  2061. // get host of a provided URL with help of an anchor object
  2062. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  2063. let parseURL = document.createElement('A');
  2064. let getHost = (url) => (parseURL.href = url, parseURL.hostname);
  2065. // site went to a new tab and attempts to unload
  2066. // call for high-level close through event
  2067. let closeWindow = () => window.dispatchEvent(new CustomEvent(eventName, {}));
  2068. // check is URL local or goes to different site
  2069. let isLocal = (url) => {
  2070. if (url === location.pathname || url === location.href)
  2071. return true; // URL points to current pathname or full address
  2072. let host = getHost(url);
  2073. let site = location.hostname;
  2074. return host !== '' && // URLs with unusual protocol may have empty 'host'
  2075. (site === host || site.endsWith(`.${host}`) || host.endsWith(`.${site}`));
  2076. };
  2077.  
  2078. let _open = window.open.bind(window);
  2079. let open = (...args) => {
  2080. '[native code]';
  2081. let url = args[0];
  2082. if (url && isLocal(url))
  2083. window.addEventListener('unload', closeWindow, true);
  2084. // jshint validthis:true
  2085. return _open(...args);
  2086. };
  2087.  
  2088. let clickHandler = (e) => {
  2089. if (!e.target.parentNode || !e.isTrusted)
  2090. window.addEventListener('unload', closeWindow, true);
  2091. };
  2092.  
  2093. createWindowOpenWrapper(open, clickHandler);
  2094.  
  2095. console.log("Background redirect prevention enabled.");
  2096. }, `let eventName="${eventName}"`, nullTools, createWindowOpenWrapper);
  2097. }
  2098.  
  2099. // Mix between check for popups and popunders
  2100. // Significantly more agressive than both and can't be used as universal solution
  2101. function preventPopMix()
  2102. {
  2103. if (inIFrame)
  2104. {
  2105. win.top.postMessage({ name: 'sandbox-me', href: win.location.href }, '*');
  2106. return;
  2107. }
  2108.  
  2109. // create "close_me" event to call high-level window.close()
  2110. let eventName = `close_me_${Math.random().toString(36).substr(2)}`;
  2111. let callClose = () => (console.log('close call'), window.close());
  2112. window.addEventListener(eventName, callClose, true);
  2113.  
  2114. scriptLander(() => {
  2115. let _open = window.open,
  2116. parseURL = document.createElement('A');
  2117. // get host of a provided URL with help of an anchor object
  2118. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  2119. let getHost = (url) => (parseURL.href = url, parseURL.host);
  2120. // site went to a new tab and attempts to unload
  2121. // call for high-level close through event
  2122. let closeWindow = () => (_open(window.location,'_self'), window.dispatchEvent(new CustomEvent(eventName, {})));
  2123. // check is URL local or goes to different site
  2124. function isLocal(url)
  2125. {
  2126. let loc = window.location;
  2127. if (url === loc.pathname || url === loc.href)
  2128. return true; // URL points to current pathname or full address
  2129. let host = getHost(url),
  2130. site = loc.host;
  2131. if (host === '')
  2132. return false; // URLs with unusual protocol may have empty 'host'
  2133. if (host.length > site.length)
  2134. [site, host] = [host, site];
  2135. return site.includes(host, site.length - host.length);
  2136. }
  2137.  
  2138. // add check for redirect for 5 seconds, then disable it
  2139. function checkRedirect()
  2140. {
  2141. window.addEventListener('unload', closeWindow, true);
  2142. setTimeout(closeWindow=>window.removeEventListener('unload', closeWindow, true), 5000, closeWindow);
  2143. }
  2144.  
  2145. function open(url, name)
  2146. {
  2147. '[native code]';
  2148. if (url && isLocal(url) && (!name || name === '_blank'))
  2149. {
  2150. console.warn('Suspicious local new window', arguments);
  2151. checkRedirect();
  2152. // jshint validthis:true
  2153. return _open.apply(this, arguments);
  2154. }
  2155. console.warn('Blocked attempt to open a new window', arguments);
  2156. return {
  2157. document: {
  2158. write: () => {},
  2159. writeln: () => {}
  2160. }
  2161. };
  2162. }
  2163.  
  2164. function clickHandler(e)
  2165. {
  2166. let link = e.target,
  2167. url = link.href||'';
  2168. if (e.targetParentNode && e.isTrusted || link.target !== '_blank')
  2169. {
  2170. console.log('Link', link, 'were created dinamically, but looks fine.');
  2171. return true;
  2172. }
  2173. if (isLocal(url) && link.target === '_blank')
  2174. {
  2175. console.log('Suspicious local link', link);
  2176. checkRedirect();
  2177. return;
  2178. }
  2179. console.log('Blocked suspicious click on a link', link);
  2180. e.stopPropagation();
  2181. e.preventDefault();
  2182. }
  2183.  
  2184. createWindowOpenWrapper(open, clickHandler);
  2185.  
  2186. console.log("Mixed popups prevention enabled.");
  2187. }, `let eventName="${eventName}"`, createWindowOpenWrapper);
  2188. }
  2189. // External listener for case when site known to open popups were loaded in iframe
  2190. // It will sandbox any iframe which will send message 'forbid.popups' (preventPopups sends it)
  2191. // Some sites replace frame's window.location with data-url to run in clean context
  2192. if (!inIFrame)
  2193. {
  2194. window.addEventListener(
  2195. 'message', function(e)
  2196. {
  2197. if (!e.data || e.data.name !== 'sandbox-me' || !e.data.href)
  2198. return;
  2199. let src = e.data.href;
  2200. for (let frame of document.querySelectorAll('iframe'))
  2201. if (frame.contentWindow === e.source)
  2202. {
  2203. if (frame.hasAttribute('sandbox'))
  2204. {
  2205. if (!frame.sandbox.contains('allow-popups'))
  2206. return; // exit frame since it's already sandboxed and popups are blocked
  2207. // remove allow-popups if frame already sandboxed
  2208. frame.sandbox.remove('allow-popups');
  2209. } else {
  2210. // set sandbox mode for troublesome frame and allow scripts, forms and a few other actions
  2211. // technically allowing both scripts and same-origin allows removal of the sandbox attribute,
  2212. // but to apply content must be reloaded and this script will re-apply it in the result
  2213. frame.setAttribute('sandbox','allow-forms allow-scripts allow-presentation allow-top-navigation allow-same-origin');
  2214. }
  2215. console.log('Disallowed popups from iframe', frame);
  2216.  
  2217. // reload frame content to apply restrictions
  2218. if (!src) {
  2219. src = frame.src;
  2220. console.log('Unable to get current iframe location, reloading from src', src);
  2221. } else
  2222. console.log('Reloading iframe with URL', src);
  2223. frame.src = 'about:blank';
  2224. frame.src = src;
  2225. }
  2226. }, false
  2227. );
  2228. }
  2229.  
  2230. function selectiveEval() {
  2231. scriptLander(() => {
  2232. let nt = new nullTools();
  2233. let _eval = win.eval.bind(window);
  2234. nt.define(win, 'eval', function(...args) {
  2235. if (/_0x|location\s*?=|location.href\s*?=|location.assign\(|open\(/i.test(args[0])) {
  2236. console.log(`Skipped eval of ${args[0].slice(0, 512)}\u2026`);
  2237. return null;
  2238. }
  2239. return _eval(...args);
  2240. });
  2241. }, nullTools);
  2242. }
  2243.  
  2244. // === Scripts for specific domains ===
  2245.  
  2246. let scripts = {};
  2247. // prevent popups and redirects block
  2248. // Popups
  2249. scripts.preventPopups = {
  2250. other: [
  2251. 'biqle.ru',
  2252. 'chaturbate.com',
  2253. 'dfiles.ru',
  2254. 'hentaiz.org',
  2255. 'mirrorcreator.com',
  2256. 'online-multy.ru',
  2257. 'radikal.ru', 'rumedia.ws', 'rustorka.com',
  2258. 'seedoff.cc', 'seedoff.tv',
  2259. 'tapochek.net', 'thepiratebay.org', 'torseed.net',
  2260. 'unionpeer.com',
  2261. 'zippyshare.com'
  2262. ],
  2263. now: preventPopups
  2264. };
  2265. // Popunders (background redirect)
  2266. scripts.preventPopunders = {
  2267. other: [
  2268. 'mediafire.com', 'megapeer.org', 'megapeer.ru',
  2269. 'perfectgirls.net'
  2270. ],
  2271. now: preventPopunders
  2272. };
  2273. // PopMix (both types of popups encountered on site)
  2274. scripts['openload.co'] = {
  2275. other: ['oload.tv', 'oload.info'],
  2276. now: () => {
  2277. let nt = new nullTools();
  2278. nt.define(win, 'CNight', win.CoinHive);
  2279. if (location.pathname.startsWith('/embed/'))
  2280. {
  2281. nt.define(win, 'BetterJsPop', {
  2282. add: ((a, b) => console.warn('BetterJsPop.add', a, b)),
  2283. config: ((o) => console.warn('BetterJsPop.config', o)),
  2284. Browser: { isChrome: true }
  2285. });
  2286. nt.define(win, 'isSandboxed', nt.func(null));
  2287. nt.define(win, 'adblock', false);
  2288. nt.define(win, 'adblock2', false);
  2289. } else
  2290. preventPopMix();
  2291. }
  2292. };
  2293. scripts['turbobit.net'] = preventPopMix;
  2294.  
  2295. // other
  2296. scripts['1tv.ru'] = () => scriptLander(() => {
  2297. let nt = new nullTools();
  2298. nt.define(win, 'EUMPAntiblockConfig', nt.proxy({url: '//www.1tv.ru/favicon.ico'}));
  2299. let _EUMPConfig = void 0;
  2300. let disablePlugins = {
  2301. 'antiblock': false,
  2302. 'stat1tv': false
  2303. };
  2304. Object.defineProperty(win, 'EUMPConfig', {
  2305. enumerable: true,
  2306. get: x => _EUMPConfig,
  2307. set: x => {
  2308. let plugins = x.plugins;
  2309. if (plugins) {
  2310. let id;
  2311. for (let plugin in disablePlugins) {
  2312. id = plugins.indexOf(plugin);
  2313. if (id > -1) {
  2314. plugins.splice(id, 1);
  2315. disablePlugins[plugin] = true;
  2316. }
  2317. }
  2318. console.warn(`Player plugins: active [${plugins}], disabled [${Object.keys(disablePlugins).filter(x => disablePlugins[x])}]`);
  2319. }
  2320. _EUMPConfig = x;
  2321. }
  2322. });
  2323. }, nullTools);
  2324.  
  2325. scripts['2picsun.ru'] = {
  2326. other: [
  2327. 'pics2sun.ru', '3pics-img.ru'
  2328. ],
  2329. now: () => {
  2330. Object.defineProperty(navigator, 'userAgent', {value: 'googlebot'});
  2331. }
  2332. };
  2333.  
  2334. scripts['4pda.ru'] = {
  2335. now: () => {
  2336. // https://greasyfork.org/en/scripts/14470-4pda-unbrender
  2337. let hStyle,
  2338. isForum = document.location.href.search('/forum/') !== -1,
  2339. remove = (node) => (node ? node.parentNode.removeChild(node) : null),
  2340. afterClean = () => remove(hStyle);
  2341.  
  2342. function beforeClean()
  2343. {
  2344. // attach styles before document displayed
  2345. hStyle = createStyle([
  2346. 'html { overflow-y: scroll }',
  2347. 'article + aside * { display: none !important }',
  2348. `section[id] {${(
  2349. 'position: absolute;'+
  2350. 'width: 100%'
  2351. )}}`,
  2352. `#header + div:after {${(
  2353. 'content: "";'+
  2354. 'position: fixed;'+
  2355. 'top: 0;'+
  2356. 'left: 0;'+
  2357. 'width: 100%;'+
  2358. 'height: 100%;'+
  2359. 'background-color: #E6E7E9'
  2360. )}}`,
  2361. // http://codepen.io/Beaugust/pen/DByiE
  2362. '@keyframes spin { 100% { transform: rotate(360deg) } }',
  2363. `article + aside:after {${(
  2364. 'content: "";'+
  2365. 'position: absolute;'+
  2366. 'width: 150px;'+
  2367. 'height: 150px;'+
  2368. 'top: 150px;'+
  2369. 'left: 50%;'+
  2370. 'margin-top: -75px;'+
  2371. 'margin-left: -75px;'+
  2372. 'box-sizing: border-box;'+
  2373. 'border-radius: 100%;'+
  2374. 'border: 10px solid rgba(0, 0, 0, 0.2);'+
  2375. 'border-top-color: rgba(0, 0, 0, 0.6);'+
  2376. 'animation: spin 2s infinite linear'
  2377. )}}`
  2378. ], {id:'ubrHider'}, true);
  2379.  
  2380. // display content of a page if time to load a page is more than 2 seconds to avoid
  2381. // blocking access to a page if it is loading for too long or stuck in a loading state
  2382. setTimeout(2000, afterClean);
  2383. }
  2384.  
  2385. createStyle([
  2386. '#nav .use-ad { display: block !important }',
  2387. 'article:not(.post) + article:not(#id),'+
  2388. 'html:not(#id)>body:not(#id) a[target="_blank"] img[height="90"] { display: none !important }'
  2389. ]);
  2390.  
  2391. if (!isForum)
  2392. beforeClean();
  2393.  
  2394. // save links to non-overridden functions to use later
  2395. let protectedElems;
  2396. // protect/hide changed attributes in case site attempt to restore them
  2397. function styleProtector(eventMode)
  2398. {
  2399. let _toLowerCase = String.prototype.toLowerCase,
  2400. isStyleText = (t) => (_toLowerCase.call(t) === 'style'),
  2401. protectedElems = new WeakMap();
  2402. function protoOverride(element, functionName, isStyleCheck, returnIfProtected)
  2403. {
  2404. let originalFunction = element.prototype[functionName];
  2405. element.prototype[functionName] = function wrapper()
  2406. {
  2407. if (protectedElems.has(this) && isStyleCheck(arguments[0]))
  2408. return returnIfProtected(this, arguments);
  2409. return originalFunction.apply(this, arguments);
  2410. };
  2411. }
  2412. protoOverride(Element, 'removeAttribute', isStyleText, () => undefined);
  2413. protoOverride(Element, 'hasAttribute', isStyleText, (_this) => protectedElems.get(_this) !== null);
  2414. protoOverride(Element, 'setAttribute', isStyleText, (_this, args) => protectedElems.set(_this, args[1]));
  2415. protoOverride(Element, 'getAttribute', isStyleText, (_this) => protectedElems.get(_this));
  2416. if (!eventMode)
  2417. return protectedElems;
  2418. else
  2419. {
  2420. let e = document.createEvent('Event');
  2421. e.initEvent('protoOverride', false, false);
  2422. window.protectedElems = protectedElems;
  2423. window.dispatchEvent(e);
  2424. }
  2425. }
  2426. if (!isFirefox)
  2427. protectedElems = styleProtector(false);
  2428. else
  2429. {
  2430. let script = document.createElement('script');
  2431. script.textContent = `(${styleProtector.toString()})(true);`;
  2432. window.addEventListener(
  2433. 'protoOverride', function protoOverrideCallback(e)
  2434. {
  2435. if (win.protectedElems) {
  2436. protectedElems = win.protectedElems;
  2437. delete win.protectedElems;
  2438. }
  2439. document.removeEventListener('protoOverride', protoOverrideCallback, true);
  2440. }, true
  2441. );
  2442. _appendChild(script);
  2443. _removeChild(script);
  2444. }
  2445.  
  2446. // clean a page
  2447. window.addEventListener(
  2448. 'DOMContentLoaded', function()
  2449. {
  2450. let width = () => window.innerWidth || _de.clientWidth || document.body.clientWidth || 0;
  2451. let height = () => window.innerHeight || _de.clientHeight || document.body.clientHeight || 0;
  2452.  
  2453. if (isForum)
  2454. {
  2455. let si = document.querySelector('#logostrip');
  2456. if (si)
  2457. remove(si.parentNode.nextSibling);
  2458. }
  2459.  
  2460. if (document.location.href.search('/forum/dl/') !== -1) {
  2461. document.body.setAttribute('style', (document.body.getAttribute('style')||'')+
  2462. ';background-color:#4ebaf6!important');
  2463. for (let itm of document.querySelectorAll('body>div'))
  2464. if (!itm.querySelector('.dw-fdwlink,.content') && !itm.classList.contains('footer'))
  2465. remove(itm);
  2466. }
  2467.  
  2468. if (isForum) // Do not continue if it's a forum
  2469. return;
  2470.  
  2471. {
  2472. let si = document.querySelector('#header');
  2473. if (si)
  2474. {
  2475. let rem = si.previousSibling;
  2476. while (rem)
  2477. {
  2478. si = rem.previousSibling;
  2479. remove(rem);
  2480. rem = si;
  2481. }
  2482. }
  2483. }
  2484.  
  2485. for (let itm of document.querySelectorAll('#nav li[class]'))
  2486. if (itm && itm.querySelector('a[href^="/tag/"]'))
  2487. remove(itm);
  2488.  
  2489. let style, result,
  2490. fakeStyles = new WeakMap(),
  2491. styleProxy = {
  2492. get: function(target, prop)
  2493. {
  2494. let fakeStyle = fakeStyles.get(target);
  2495. return ((prop in fakeStyle) ? fakeStyle : target)[prop];
  2496. },
  2497. set: function(target, prop, value)
  2498. {
  2499. let fakeStyle = fakeStyles.get(target);
  2500. ((prop in fakeStyle) ? fakeStyle : target)[prop] = value;
  2501. return true;
  2502. }
  2503. };
  2504. for (let itm of document.querySelectorAll('DIV, A'))
  2505. {
  2506. if (itm.tagName ==='DIV' &&
  2507. itm.offsetWidth > 0.95 * width() &&
  2508. itm.offsetHeight > 0.85 * height())
  2509. {
  2510. style = window.getComputedStyle(itm, null);
  2511. result = [];
  2512.  
  2513. if (style.backgroundImage !== 'none')
  2514. result.push('background-image:none!important');
  2515.  
  2516. if (style.backgroundColor !== 'transparent' &&
  2517. style.backgroundColor !== 'rgba(0, 0, 0, 0)')
  2518. result.push('background-color:transparent!important');
  2519.  
  2520. if (result.length)
  2521. {
  2522. if (itm.getAttribute('style'))
  2523. result.unshift(itm.getAttribute('style'));
  2524.  
  2525. fakeStyles.set(itm.style, {
  2526. 'backgroundImage': itm.style.backgroundImage,
  2527. 'backgroundColor': itm.style.backgroundColor
  2528. });
  2529.  
  2530. try {
  2531. Object.defineProperty(itm, 'style', {
  2532. value: new Proxy(itm.style, styleProxy),
  2533. enumerable: true
  2534. });
  2535. } catch (e) {
  2536. console.log('Unable to protect style property.', e);
  2537. }
  2538.  
  2539. if (protectedElems)
  2540. protectedElems.set(itm, _getAttribute.call(itm, 'style'));
  2541.  
  2542. _setAttribute.call(itm, 'style', result.join(';'));
  2543. }
  2544. }
  2545. if (itm.tagName ==='A' &&
  2546. (itm.offsetWidth > 0.95 * width() ||
  2547. itm.offsetHeight > 0.85 * height()))
  2548. {
  2549. if (protectedElems)
  2550. protectedElems.set(itm, _getAttribute.call(itm, 'style'));
  2551.  
  2552. _setAttribute.call(itm, 'style', 'display:none!important');
  2553. }
  2554. }
  2555.  
  2556. for (let itm of document.querySelectorAll('ASIDE>DIV'))
  2557. if ( ((itm.querySelector('script, iframe, a[href*="/ad/www/"]') ||
  2558. itm.querySelector('img[src$=".gif"]:not([height="0"]), img[height="400"]')) &&
  2559. !itm.classList.contains('post') ) || !itm.childNodes.length )
  2560. remove(itm);
  2561.  
  2562. document.body.setAttribute('style', (document.body.getAttribute('style')||'')+';background-color:#E6E7E9!important');
  2563.  
  2564. // display content of the page
  2565. afterClean();
  2566. }
  2567. );
  2568. }
  2569. };
  2570.  
  2571. scripts['adhands.ru'] = () => scriptLander(() => {
  2572. let nt = new nullTools();
  2573. try {
  2574. let _adv;
  2575. Object.defineProperty(win, 'adv', {
  2576. get: () => _adv,
  2577. set: (v) => {
  2578. console.log('Blocked advert on adhands.ru.');
  2579. nt.define(v, 'advert', '');
  2580. _adv = v;
  2581. }
  2582. });
  2583. } catch (ignore) {
  2584. if (!win.adv)
  2585. console.log('Unable to locate advert on adhands.ru.');
  2586. else {
  2587. console.log('Blocked advert on adhands.ru.');
  2588. nt.define(win.adv, 'advert', '');
  2589. }
  2590. }
  2591. }, nullTools);
  2592.  
  2593. scripts['allhentai.ru'] = () => {
  2594. selectiveEval();
  2595. preventPopups();
  2596. scriptLander(() => {
  2597. let _onerror = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onerror');
  2598. if (!_onerror)
  2599. return;
  2600. _onerror.set = (...args) => console.log(args[0].toString());
  2601. Object.defineProperty(HTMLElement.prototype, 'onerror', _onerror);
  2602. });
  2603. };
  2604.  
  2605. scripts['allmovie.pro'] = {
  2606. other: ['rufilmtv.org'],
  2607. dom: function()
  2608. {
  2609. // pretend to be Android to make site use different played for ads
  2610. if (isSafari)
  2611. return;
  2612. Object.defineProperty(navigator, 'userAgent', {
  2613. 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'; },
  2614. enumerable: true
  2615. });
  2616. }
  2617. };
  2618.  
  2619. scripts['anidub-online.ru'] = {
  2620. other: ['online.anidub.com'],
  2621. dom: function()
  2622. {
  2623. if (win.ogonekstart1)
  2624. win.ogonekstart1 = () => console.log("Fire in the hole!");
  2625. },
  2626. now: () => createStyle([
  2627. '.background {background: none!important;}',
  2628. '.background > script + div,'+
  2629. '.background > script ~ div:not([id]):not([class]) + div[id][class]'+
  2630. '{display:none!important}'
  2631. ])
  2632. };
  2633.  
  2634. scripts['drive2.ru'] = () => gardener('.c-block:not([data-metrika="recomm"]),.o-grid__item', />Реклама<\//i);
  2635.  
  2636. scripts['fishki.net'] = () => {
  2637. scriptLander(() => {
  2638. let nt = new nullTools();
  2639. let fishki = {};
  2640. nt.define(fishki, 'adv', nt.proxy({
  2641. afterAdblockCheck: nt.func(null),
  2642. refreshFloat: nt.func(null)
  2643. }));
  2644. nt.define(fishki, 'is_adblock', false);
  2645. nt.define(win, 'fishki', fishki);
  2646. }, nullTools);
  2647. gardener('.drag_list > .drag_element, .list-view > .paddingtop15, .post-wrap', /543769|Новости\sпартнеров|Полезная\sреклама/);
  2648. };
  2649.  
  2650. scripts['gidonline.club'] = () => createStyle('.tray > div[style] {display: none!important}');
  2651.  
  2652. scripts['hdgo.cc'] = {
  2653. other: ['46.30.43.38', 'couber.be'],
  2654. now: () => (new MutationObserver(
  2655. (ms) => {
  2656. let m, node;
  2657. for (m of ms) for (node of m.addedNodes)
  2658. if (node.tagName instanceof HTMLScriptElement && _getAttribute.call(node, 'onerror') !== null)
  2659. node.removeAttribute('onerror');
  2660. }
  2661. )).observe(document.documentElement, { childList:true, subtree: true })
  2662. };
  2663.  
  2664. scripts['gismeteo.ru'] = {
  2665. other: ['gismeteo.ua'],
  2666. now: () => gardener('div > script', /AdvManager/i, { observe: true, parent: 'div' })
  2667. };
  2668.  
  2669. scripts['hdrezka.ag'] = () => {
  2670. Object.defineProperty(win, 'ab', { value: false, enumerable: true });
  2671. gardener('div[id][onclick][onmouseup][onmousedown]', /onmouseout/i);
  2672. };
  2673.  
  2674. scripts['hideip.me'] = {
  2675. now: () => scriptLander(() => {
  2676. let _innerHTML = Object.getOwnPropertyDescriptor(Element.prototype, 'innerHTML');
  2677. let _set_innerHTML = _innerHTML.set;
  2678. let _innerText = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'innerText');
  2679. let _get_innerText = _innerText.get;
  2680. let div = document.createElement('div');
  2681. _innerHTML.set = function(...args) {
  2682. _set_innerHTML.call(div, args[0].replace('i','a'));
  2683. if (args[0] && /[рp][еe]кл/.test(_get_innerText.call(div))||
  2684. /(\d\d\d?\.){3}\d\d\d?\:\d/.test(_get_innerText.call(this)) ) {
  2685. console.log('Anti-Adblock killed.');
  2686. return true;
  2687. }
  2688. _set_innerHTML.apply(this, args);
  2689. };
  2690. Object.defineProperty(Element.prototype, 'innerHTML', _innerHTML);
  2691. Object.defineProperty(win, 'adblock', {
  2692. get: x => false,
  2693. set: x => null,
  2694. enumerable: true
  2695. });
  2696. let _$ = {};
  2697. let _$_map = new WeakMap();
  2698. let _gOPD = Object.getOwnPropertyDescriptor(Object, 'getOwnPropertyDescriptor');
  2699. let _val_gOPD = _gOPD.value;
  2700. _gOPD.value = function(...args) {
  2701. let _res = _val_gOPD.apply(this, args);
  2702. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery')) {
  2703. delete _res.get;
  2704. delete _res.set;
  2705. _res.value = win[args[1]];
  2706. }
  2707. return _res;
  2708. };
  2709. Object.defineProperty(Object, 'getOwnPropertyDescriptor', _gOPD);
  2710. let getJQWrap = (n) => {
  2711. let name = n;
  2712. return {
  2713. enumerable: true,
  2714. get: x => _$[name],
  2715. set: x => {
  2716. if (_$_map.has(x)) {
  2717. _$[name] = _$_map.get(x);
  2718. return true;
  2719. }
  2720. if (x === _$.$ || x === _$.jQuery) {
  2721. _$[name] = x;
  2722. return true;
  2723. }
  2724. _$[name] = new Proxy(x, {
  2725. apply: (t, o, args) => {
  2726. let _res = t.apply(o, args);
  2727. if (_$_map.has(_res.is)) {
  2728. _res.is = _$_map.get(_res.is);
  2729. } else {
  2730. let _is = _res.is;
  2731. _res.is = function(...args) {
  2732. if (args[0] === ':hidden')
  2733. return false;
  2734. return _is.apply(this, args);
  2735. };
  2736. _$_map.set(_is, _res.is);
  2737. }
  2738. return _res;
  2739. }
  2740. });
  2741. _$_map.set(x, _$[name]);
  2742. return true;
  2743. }
  2744. };
  2745. };
  2746. Object.defineProperty(win, '$', getJQWrap('$'));
  2747. Object.defineProperty(win, 'jQuery', getJQWrap('jQuery'));
  2748. let _dP = Object.defineProperty;
  2749. Object.defineProperty = function(...args) {
  2750. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery'))
  2751. return void 0;
  2752. return _dP.apply(this, args);
  2753. };
  2754. })
  2755. };
  2756.  
  2757. scripts['imageban.ru'] = {
  2758. now: preventPopunders,
  2759. dom: () => win.addEventListener('unload', () => location.hash = 'x'+Math.random().toString(36).substr(2), true)
  2760. };
  2761.  
  2762. scripts['kinopoisk.ru'] = {
  2763. now: () => {
  2764. // set no-branding body style
  2765. createStyle('body:not(#id) { background: #d5d5d5 url(/images/noBrandBg.jpg) 50% 0 no-repeat !important }');
  2766. },
  2767. dom: () => {
  2768. (style => style ? style.parentNode.removeChild(style) : console.log('Unable to locate branding style.')
  2769. )(_de.querySelector('#branding-style'));
  2770. }
  2771. };
  2772.  
  2773. scripts['mail.ru'] = () => scriptLander(() => {
  2774. let nt = new nullTools();
  2775. // Trick to prevent mail.ru from removing 3rd-party styles
  2776. nt.define(Object.prototype, 'restoreVisibility', nt.func(null), false);
  2777. // Disable some of their counters
  2778. nt.define(win, 'rb_counter', nt.func(null, 'rb_counter'));
  2779. if (location.hostname !== 'e.mail.ru')
  2780. nt.define(win, 'createRadar', nt.func(nt.func(null, 'aRadar'), 'createRadar'));
  2781. else
  2782. nt.define(win, 'aRadar', nt.func(null, 'aRadar'));
  2783.  
  2784. // Disable page scrambler on mail.ru to let extensions easily block ads there
  2785. function defineLocator(root)
  2786. {
  2787. let _locator;
  2788. let fishnet = {
  2789. apply: (target, thisArg, args) => {
  2790. console.log(`locator.${target._name}(${JSON.stringify(args).slice(1,-1)})`);
  2791. return target.apply(thisArg, args);
  2792. }
  2793. };
  2794.  
  2795. function wrapLocator(locator)
  2796. {
  2797. if ('setup' in locator)
  2798. {
  2799. let _setup = locator.setup;
  2800. locator.setup = function(o)
  2801. {
  2802. if ('enable' in o)
  2803. {
  2804. o.enable = false;
  2805. console.log('Disable mimic mode.');
  2806. }
  2807. if ('links' in o)
  2808. {
  2809. o.links = [];
  2810. console.log('Call with empty list of sheets.');
  2811. }
  2812. return _setup.call(this, o);
  2813. };
  2814. locator.insertSheet = () => console.log('Ignore insertSheet.');
  2815. locator.wrap = () => console.log('Ignore wrap.');
  2816. }
  2817. try {
  2818. let names = [];
  2819. for (let name in locator)
  2820. if (locator[name] instanceof Function) {
  2821. locator[name]._name = name;
  2822. locator[name] = new Proxy(locator[name], fishnet);
  2823. names.push(name);
  2824. }
  2825. console.log(`[locator] wrapped properties: ${names.join(', ')}`);
  2826. } catch(e) {
  2827. console.log(e);
  2828. }
  2829. _locator = locator;
  2830. }
  2831.  
  2832. if ('locator' in root && root.locator)
  2833. {
  2834. console.log('Found existing "locator" object. :|');
  2835. _locator = root.locator;
  2836. wrapLocator(root.locator);
  2837. }
  2838.  
  2839. let loc_desc = Object.getOwnPropertyDescriptor(root, 'locator');
  2840. if (!loc_desc || loc_desc.set !== wrapLocator)
  2841. try {
  2842. Object.defineProperty(root, 'locator', {
  2843. set: wrapLocator,
  2844. get: () => _locator
  2845. });
  2846. } catch (err) {
  2847. console.log('Unable to redefine "locator" object!!!', err);
  2848. }
  2849. }
  2850.  
  2851. function defineDetector(mr)
  2852. {
  2853. let __ = mr._ || {};
  2854.  
  2855. if ('HONEYPOT' in __)
  2856. {
  2857. console.log('Disarming existing detector instance. :|', JSON.stringify(__));
  2858. nt.define(__, 'HONEYPOT', '.honeypot_fake_class_to_miss');
  2859. nt.define(__, 'STUCK_IN_POT', false);
  2860. }
  2861.  
  2862. __ = new Proxy(__, {
  2863. get: (t, p) => t[p],
  2864. set: (t, p, v) => {
  2865. console.log(`mr._.${p} =`, v);
  2866. if (['HONEYPOT', 'STUCK_IN_POT'].includes(p))
  2867. console.log('Not changed.');
  2868. t[p] = v; // setter in nt.define will prevent this when needed
  2869. return true;
  2870. }
  2871. });
  2872. Object.defineProperty(mr, '_', {
  2873. enumerable: true,
  2874. value: __
  2875. });
  2876. }
  2877.  
  2878. if (location.hostname === 'e.mail.ru')
  2879. defineLocator(win);
  2880. else {
  2881. try {
  2882. let _mr;
  2883. Object.defineProperty(win, 'mr', {
  2884. enumerable: true,
  2885. get: () => _mr,
  2886. set: (v) => {
  2887. if (v === _mr)
  2888. return true;
  2889. console.log('Trapped new "mr" object.');
  2890. defineLocator(v.mimic ? v.mimic : v);
  2891. defineDetector(v);
  2892. _mr = v;
  2893. }
  2894. });
  2895. if (!('mr' in win))
  2896. throw 'Wat!?';
  2897. } catch (e) {
  2898. console.log('Found existing "mr" object.', e instanceof TypeError ? '' : e);
  2899. defineLocator(win.mr);
  2900. defineDetector(win.mr);
  2901. }
  2902. }
  2903. }, nullTools);
  2904.  
  2905. scripts['megogo.net'] = {
  2906. now: () => {
  2907. let nt = new nullTools();
  2908. nt.define(win, 'adBlock', false);
  2909. nt.define(win, 'showAdBlockMessage', nt.func(null));
  2910. }
  2911. };
  2912.  
  2913. scripts['naruto-base.su'] = () => gardener('div[id^="entryID"],.block', /href="http.*?target="_blank"/i);
  2914.  
  2915. scripts['overclockers.ru'] = {
  2916. now: () => scriptLander(() => {
  2917. let _innerHTML = Object.getOwnPropertyDescriptor(Element.prototype, 'innerHTML');
  2918. let _set_innerHTML = _innerHTML.set;
  2919. _innerHTML.set = function() {
  2920. if (this === document.body) {
  2921. console.log('Anti-Adblock killed.');
  2922. return true;
  2923. }
  2924. _set_innerHTML.apply(this, arguments);
  2925. };
  2926. Object.defineProperty(Element.prototype, 'innerHTML', _innerHTML);
  2927. })
  2928. };
  2929. scripts['forums.overclockers.ru'] = {
  2930. now: () => {
  2931. createStyle('.needblock {position: fixed; left: -10000px}');
  2932. Object.defineProperty(win, 'adblck', {
  2933. get: () => 'no',
  2934. set: () => undefined,
  2935. enumerable: true
  2936. });
  2937. }
  2938. };
  2939.  
  2940. scripts['pb.wtf'] = {
  2941. other: ['piratbit.org', 'piratbit.ru'],
  2942. now: () => {
  2943. // line above topic content and images in the slider in the header
  2944. gardener(
  2945. 'a[href^="/exit/"], a[href^="/fxt/"], a[href$="=="]',
  2946. /img|Реклама|center/i,
  2947. { root: '.release-navbar,#page_content', observe: true, parent: 'div,tr' }
  2948. );
  2949. // ads in comments
  2950. gardener('img[data-name="PiraBo"]', /./i, {root:'#main_content .table', observe:true, parent:'tr'});
  2951. }
  2952. };
  2953.  
  2954. scripts['pikabu.ru'] = () => gardener('.story', /story__author[^>]+>ads</i, {root: '.inner_wrap', observe: true});
  2955.  
  2956. scripts['qrz.ru'] = {
  2957. now: () => {
  2958. let nt = new nullTools();
  2959. nt.define(win, 'ab', false);
  2960. nt.define(win, 'tryMessage', nt.func(null));
  2961. }
  2962. };
  2963.  
  2964. scripts['razlozhi.ru'] = {
  2965. now: () => {
  2966. for (let func of ['createShadowRoot', 'attachShadow'])
  2967. if (func in Element.prototype)
  2968. Element.prototype[func] = function(){ return this.cloneNode(); };
  2969. }
  2970. };
  2971.  
  2972. scripts['rbc.ru'] = {
  2973. dom: () => {
  2974. let _preventDefault = Event.prototype.preventDefault;
  2975. Event.prototype.preventDefault = function preventDefault()
  2976. {
  2977. let t = this.target;
  2978. if (t instanceof HTMLAnchorElement || t.closest('A'))
  2979. throw new Error('an.yandex redirect prevention');
  2980. return _preventDefault.call(this);
  2981. };
  2982.  
  2983. function cleaner(nodes)
  2984. {
  2985. for (let node of nodes)
  2986. {
  2987. if (!node.classList || !node.classList.contains('js-yandex-counter'))
  2988. continue;
  2989. node.classList.remove('js-yandex-counter');
  2990. node.removeAttribute('data-yandex-name');
  2991. node.removeAttribute('data-yandex-params');
  2992. }
  2993. }
  2994. cleaner(_de.querySelectorAll('.js-yandex-counter'));
  2995.  
  2996. (new MutationObserver(
  2997. ms => { for (let m of ms) cleaner(m.addedNodes); }
  2998. )).observe(_de, {childList: true, subtree: true});
  2999. }
  3000. };
  3001.  
  3002. scripts['rp5.ru'] = {
  3003. other: ['rp5.by', 'rp5.kz', 'rp5.ua'],
  3004. now: () => gardener('div[id][class]', /\?AdvertMgmt=|adsbygoogle/, { root: '#content-wrapper', log: true })
  3005. };
  3006.  
  3007. scripts['spaces.ru'] = () => {
  3008. gardener('div > a[href^="http://spaces.ru/?Cl="]', /./, { parent: 'div' });
  3009. gardener('.js-banner_rotator', /./, { parent: '.widgets-group' });
  3010. };
  3011.  
  3012. scripts['spam-club.blogspot.co.uk'] = () => {
  3013. let _clientHeight = Object.getOwnPropertyDescriptor(Element.prototype, 'clientHeight'),
  3014. _clientWidth = Object.getOwnPropertyDescriptor(Element.prototype, 'clientWidth');
  3015. let wrapGetter = (getter) => {
  3016. let _getter = getter;
  3017. return function()
  3018. {
  3019. let _size = _getter.apply(this, arguments);
  3020. return _size ? _size : 1;
  3021. };
  3022. };
  3023. _clientHeight.get = wrapGetter(_clientHeight.get);
  3024. _clientWidth.get = wrapGetter(_clientWidth.get);
  3025. Object.defineProperty(Element.prototype, 'clientHeight', _clientHeight);
  3026. Object.defineProperty(Element.prototype, 'clientWidth', _clientWidth);
  3027. let _onload = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onload'),
  3028. _set_onload = _onload.set;
  3029. _onload.set = function()
  3030. {
  3031. if (this instanceof HTMLImageElement)
  3032. return true;
  3033. _set_onload.apply(this, arguments);
  3034. };
  3035. Object.defineProperty(HTMLElement.prototype, 'onload', _onload);
  3036. };
  3037.  
  3038. scripts['sport-express.ru'] = () => gardener('.js-relap__item',/>Реклама\s+<\//, {root:'.container', observe: true});
  3039.  
  3040. scripts['sports.ru'] = {
  3041. now: () => {
  3042. gardener('.aside-news-list__item', /aside-news-list__advert/i, {root:'.columns-layout__left', observe: true});
  3043. gardener('.material-list__item', /Реклама/i, {root:'.columns-layout', observe: true});
  3044. // extra functionality: shows/hides panel at the top depending on scroll direction
  3045. createStyle([
  3046. '.user-panel__fixed { transition: top 0.2s ease-in-out!important; }',
  3047. '.user-panel-up { top: -40px!important }'
  3048. ], {id: 'userPanelSlide'}, false);
  3049. },
  3050. dom: () => {
  3051. (function lookForPanel()
  3052. {
  3053. let panel = document.querySelector('.user-panel__fixed');
  3054. if (!panel)
  3055. setTimeout(lookForPanel, 100);
  3056. else
  3057. window.addEventListener(
  3058. 'wheel', function(e)
  3059. {
  3060. if (e.deltaY > 0 && !panel.classList.contains('user-panel-up'))
  3061. panel.classList.add('user-panel-up');
  3062. else if (e.deltaY < 0 && panel.classList.contains('user-panel-up'))
  3063. panel.classList.remove('user-panel-up');
  3064. }, false
  3065. );
  3066. })();
  3067. }
  3068. };
  3069.  
  3070. scripts['vk.com'] = () => gardener((
  3071. '#wk_content > #wl_post > div,'+
  3072. '#page_wall_posts > div[id^="post-"],'+
  3073. 'div[class^="feed_row "] > div[id^="post-"],'+
  3074. 'div[class^="feed_row "] > div[id^="feed_repost-"]'
  3075. ), /wall_marked_as_ads/, {root: 'body', observe: true});
  3076.  
  3077. scripts['yap.ru'] = {
  3078. other: ['yaplakal.com'],
  3079. now: () => {
  3080. gardener('form > table[id^="p_row_"]:nth-of-type(2)', /member1438|Administration/);
  3081. gardener('.icon-comments', /member1438|Administration|\/go\/\?http/, {parent:'tr', siblings:-2});
  3082. }
  3083. };
  3084.  
  3085. scripts['rambler.ru'] = {
  3086. other: ['championat.com','gazeta.ru','media.eagleplatform.com','lenta.ru', 'quto.ru'],
  3087. now: () => scriptLander(() => {
  3088. // Prevent autoplay
  3089. if (!('EaglePlayer' in win)) {
  3090. let _EaglePlayer = void 0;
  3091. Object.defineProperty(win, 'EaglePlayer', {
  3092. enumerable: true,
  3093. get: x => _EaglePlayer,
  3094. set: x => {
  3095. if (x === _EaglePlayer)
  3096. return true;
  3097. _EaglePlayer = x;
  3098. let _init = void 0;
  3099. Object.defineProperty(_EaglePlayer.prototype, 'init', {
  3100. enumerable: true,
  3101. set: x => _init = x,
  3102. get: function() {
  3103. let _self = this;
  3104. if (_self.options) {
  3105. Object.defineProperty(this.options, 'autoplay', {
  3106. enumerable: true,
  3107. get: x => false,
  3108. set: x => null
  3109. });
  3110. }
  3111. if (_self.options && _self.options.el && inIFrame) {
  3112. let addListener = (player) => {
  3113. console.log('Attached autostop');
  3114. player.addEventListener('canplay', e => {
  3115. e.target.play = () => console.log('Applied autostop.');
  3116. setTimeout(player => {
  3117. delete player.play;
  3118. console.log('Detached autostop');
  3119. }, 1500, e.target);
  3120. }, false);
  3121. };
  3122. (new MutationObserver(ms => {
  3123. let m, node;
  3124. for (m of ms) for (node of m.addedNodes)
  3125. if (node instanceof HTMLVideoElement)
  3126. addListener(node);
  3127. })).observe(this.options.el, { childList: true, subtree: true });
  3128. }
  3129. return _init;
  3130. }
  3131. });
  3132. }
  3133. });
  3134. let _setAttribute = Element.prototype.setAttribute;
  3135. let isAutoplay = /^autoplay$/i;
  3136. Element.prototype.setAttribute = function setAttribute(name)
  3137. {
  3138. if (!this._stopped && isAutoplay.test(name))
  3139. {
  3140. console.log('Prevented assigning autoplay attribute.');
  3141. return null;
  3142. }
  3143. return _setAttribute.apply(this, arguments);
  3144. };
  3145. } else if (inIFrame) {
  3146. let _setAttribute = Element.prototype.setAttribute;
  3147. let isAutoplay = /^autoplay$/i;
  3148. Element.prototype.setAttribute = function setAttribute(name)
  3149. {
  3150. if (!this._stopped && isAutoplay.test(name))
  3151. {
  3152. console.log('Prevented assigning autoplay attribute.');
  3153. this._stopped = true;
  3154. this.play = () => {
  3155. console.log('Prevented attempt to force-start playback.');
  3156. delete this.play;
  3157. };
  3158. return null;
  3159. }
  3160. return _setAttribute.apply(this, arguments);
  3161. };
  3162. }
  3163. if (location.hostname.endsWith('.media.eagleplatform.com'))
  3164. return;
  3165. let CSSRuleProto = 'cssText' in CSSRule.prototype ? CSSRule.prototype : CSSStyleRule.prototype;
  3166. let _cssText = Object.getOwnPropertyDescriptor(CSSRuleProto, 'cssText');
  3167. let _cssText_get = _cssText.get;
  3168. _cssText.configurable = false;
  3169. _cssText.get = function()
  3170. {
  3171. let cssText = _cssText_get.call(this);
  3172. if (cssText.includes('content:'))
  3173. {
  3174. console.log('Blocked access to suspicious cssText:', cssText.slice(0,60), '\u2026', cssText.length);
  3175. return null;
  3176. }
  3177. return cssText;
  3178. };
  3179. Object.defineProperty(CSSRuleProto, 'cssText', _cssText);
  3180. // fake global Adf object
  3181. let nt = new nullTools();
  3182. let ssPromise = nt.func(new Promise((r,j) => r({status: true})));
  3183. nt.define(win, 'Adf', nt.proxy({
  3184. banner: nt.proxy({
  3185. sspScroll: ssPromise,
  3186. ssp: ssPromise
  3187. })
  3188. }));
  3189. // extra script to remove partner news on gazeta.ru
  3190. if (!location.hostname.includes('gazeta.ru'))
  3191. return;
  3192. (new MutationObserver(
  3193. (ms) => {
  3194. let m, node, header;
  3195. for (m of ms) for (node of m.addedNodes)
  3196. if (node instanceof HTMLDivElement && node.matches('.sausage'))
  3197. {
  3198. header = node.querySelector('.sausage-header');
  3199. if (header && /новости\s+партн[её]ров/i.test(header.textContent))
  3200. node.style.display = 'none';
  3201. }
  3202. }
  3203. )).observe(document.documentElement, { childList:true, subtree: true });
  3204. }, `let inIFrame = ${inIFrame}`, nullTools)
  3205. };
  3206.  
  3207. scripts['reactor.cc'] = {
  3208. other: ['joyreactor.cc', 'pornreactor.cc'],
  3209. now: () => {
  3210. selectiveEval();
  3211. scriptLander(() => {
  3212. let nt = new nullTools();
  3213. win.open = (function(){ throw new Error('Redirect prevention.'); }).bind(window);
  3214. nt.define(win, 'Worker', function(){});
  3215. nt.define(win, 'JRCH', win.CoinHive);
  3216. }, nullTools);
  3217. },
  3218. click: function(e)
  3219. {
  3220. let node = e.target;
  3221. if (node.nodeType === Node.ELEMENT_NODE &&
  3222. node.style.position === 'absolute' &&
  3223. node.style.zIndex > 0)
  3224. node.parentNode.removeChild(node);
  3225. },
  3226. dom: function()
  3227. {
  3228. let words = new RegExp(
  3229. 'блокировщик рекламы'
  3230. .split('')
  3231. .map(function(e){return e+'[\u200b\u200c\u200d]*';})
  3232. .join('')
  3233. .replace(' ', '\\s*')
  3234. .replace(/[аоре]/g, function(e){return ['[аa]','[оo]','[рp]','[еe]']['аоре'.indexOf(e)];}),
  3235. 'i'),
  3236. can;
  3237. function deeper(spider)
  3238. {
  3239. let c, l, n;
  3240. if (words.test(spider.innerText))
  3241. {
  3242. if (spider.nodeType === Node.TEXT_NODE)
  3243. return true;
  3244. c = spider.childNodes;
  3245. l = c.length;
  3246. n = 0;
  3247. while(l--)
  3248. if (deeper(c[l]), can)
  3249. n++;
  3250. if (n > 0 && n === c.length && spider.offsetHeight < 750)
  3251. can.push(spider);
  3252. return false;
  3253. }
  3254. return true;
  3255. }
  3256. function probe()
  3257. {
  3258. if (words.test(document.body.innerText))
  3259. {
  3260. can = [];
  3261. deeper(document.body);
  3262. let i = can.length, spider;
  3263. while(i--) {
  3264. spider = can[i];
  3265. if (spider.offsetHeight > 10 && spider.offsetHeight < 750)
  3266. _setAttribute.call(spider, 'style', 'background:none!important');
  3267. }
  3268. }
  3269. }
  3270. (new MutationObserver(probe))
  3271. .observe(document, { childList:true, subtree:true });
  3272. }
  3273. };
  3274.  
  3275. scripts['auto.ru'] = () => {
  3276. let words = /Реклама|Яндекс.Директ|yandex_ad_/;
  3277. let userAdsListAds = (
  3278. '.listing-list > .listing-item,'+
  3279. '.listing-item_type_fixed.listing-item'
  3280. );
  3281. let catalogAds = (
  3282. 'div[class*="layout_catalog-inline"],'+
  3283. 'div[class$="layout_horizontal"]'
  3284. );
  3285. let otherAds = (
  3286. '.advt_auto,'+
  3287. '.sidebar-block,'+
  3288. '.pager-listing + div[class],'+
  3289. '.card > div[class][style],'+
  3290. '.sidebar > div[class],'+
  3291. '.main-page__section + div[class],'+
  3292. '.listing > tbody'
  3293. );
  3294. gardener(userAdsListAds, words, {root:'.listing-wrap', observe:true});
  3295. gardener(catalogAds, words, {root:'.catalog__page,.content__wrapper', observe:true});
  3296. gardener(otherAds, words);
  3297. };
  3298.  
  3299. scripts['rsload.net'] = {
  3300. load: () => {
  3301. let dis = document.querySelector('label[class*="cb-disable"]');
  3302. if (dis)
  3303. dis.click();
  3304. },
  3305. click: () => {
  3306. let t = e.target;
  3307. if (t && t.href && (/:\/\/\d+\.\d+\.\d+\.\d+\//.test(t.href)))
  3308. t.href = t.href.replace('://','://rsload.net:rsload.net@');
  3309. }
  3310. };
  3311.  
  3312. let domain;
  3313. // add alternative domain names if present and wrap functions into objects
  3314. for (let name in scripts)
  3315. {
  3316. if (scripts[name] instanceof Function)
  3317. scripts[name] = { now: scripts[name] };
  3318. for (domain of (scripts[name].other||[]))
  3319. {
  3320. if (domain in scripts)
  3321. console.log('Error in scripts list. Script for', name, 'replaced script for', domain);
  3322. scripts[domain] = scripts[name];
  3323. }
  3324. delete scripts[name].other;
  3325. }
  3326. // look for current domain in the list and run appropriate code
  3327. domain = document.domain;
  3328. while (domain.indexOf('.') > -1)
  3329. {
  3330. if (domain in scripts) for (let when in scripts[domain])
  3331. switch(when)
  3332. {
  3333. case 'now':
  3334. scripts[domain][when]();
  3335. break;
  3336. case 'dom':
  3337. document.addEventListener('DOMContentLoaded', scripts[domain][when], false);
  3338. break;
  3339. default:
  3340. document.addEventListener (when, scripts[domain][when], false);
  3341. }
  3342. domain = domain.slice(domain.indexOf('.') + 1);
  3343. }
  3344. })();