RU AdList JS Fixes

try to take over the world!

目前为 2018-02-09 提交的版本,查看 最新版本

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