RU AdList JS Fixes

try to take over the world!

当前为 2018-02-12 提交的版本,查看 最新版本

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