RU AdList JS Fixes

try to take over the world!

目前為 2018-02-08 提交的版本,檢視 最新版本

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