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