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.2
  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|46p5gi\.ru|k5evib\.ru|v6t39t\.ru)[:/]/i;
  1846. // blacklist of domains where all third-party requests are ignored
  1847. let ondomains = /(^|[/.@])oane\.ws($|[:/])/i;
  1848.  
  1849. XMLHttpRequest.prototype.open = function(method, url)
  1850. {
  1851. if (method === 'GET' && (blacklist.test(url) ||
  1852. ondomains.test(location.hostname) && !ondomains.test(url)))
  1853. {
  1854. this.send = () => null;
  1855. this.setRequestHeader = () => null;
  1856. console.log('Blocked request: ', url);
  1857. return;
  1858. }
  1859. return _open.apply(this, arguments);
  1860. };
  1861. }
  1862. );
  1863.  
  1864. // === Helper functions ===
  1865.  
  1866. // function to search and remove nodes by content
  1867. // selector - standard CSS selector to define set of nodes to check
  1868. // words - regular expression to check content of the suspicious nodes
  1869. // params - object with multiple extra parameters:
  1870. // .log - display log in the console
  1871. // .hide - set display to none instead of removing from the page
  1872. // .parent - parent node to remove if content is found in the child node
  1873. // .siblings - number of simling nodes to remove (excluding text nodes)
  1874. let scRemove = (node) => node.parentNode.removeChild(node);
  1875. let scHide = function(node)
  1876. {
  1877. let style = _getAttribute.call(node, 'style') || '',
  1878. hide = ';display:none!important;';
  1879. if (style.indexOf(hide) < 0)
  1880. _setAttribute.call(node, 'style', style + hide);
  1881. };
  1882.  
  1883. function scissors (selector, words, scope, params)
  1884. {
  1885. let logger = function() { return params.log ? console.log(...arguments) : null; };
  1886. if (!scope.contains(document.body))
  1887. logger('[s] scope', scope);
  1888. let remFunc = (params.hide ? scHide : scRemove),
  1889. iterFunc = (params.siblings > 0 ? 'nextElementSibling' : 'previousElementSibling'),
  1890. toRemove = [],
  1891. siblings;
  1892. for (let node of scope.querySelectorAll(selector))
  1893. {
  1894. // drill up to a parent node if specified, break if not found
  1895. if (params.parent)
  1896. {
  1897. let old = node;
  1898. node = node.closest(params.parent);
  1899. if (node === null || node.contains(scope))
  1900. {
  1901. logger('[s] went out of scope with', old);
  1902. continue;
  1903. }
  1904. }
  1905. logger('[s] processing', node);
  1906. if (toRemove.includes(node))
  1907. continue;
  1908. if (words.test(node.innerHTML))
  1909. {
  1910. // skip node if already marked for removal
  1911. logger('[s] marked for removal');
  1912. toRemove.push(node);
  1913. // add multiple nodes if defined more than one sibling
  1914. siblings = Math.abs(params.siblings) || 0;
  1915. while (siblings)
  1916. {
  1917. node = node[iterFunc];
  1918. if (!node) break; // can't go any further - exit
  1919. logger('[s] adding sibling node', node);
  1920. toRemove.push(node);
  1921. siblings -= 1;
  1922. }
  1923. }
  1924. }
  1925. let toSkip = [];
  1926. for (let node of toRemove)
  1927. if (!toRemove.every(other => other === node || !node.contains(other)))
  1928. toSkip.push(node);
  1929. if (toRemove.length)
  1930. logger(`[s] proceeding with ${params.hide?'hide':'removal'} of`, toRemove, `skip`, toSkip);
  1931. for (let node of toRemove) if (!toSkip.includes(node))
  1932. remFunc(node);
  1933. }
  1934.  
  1935. // function to perform multiple checks if ads inserted with a delay
  1936. // by default does 30 checks withing a 3 seconds unless nonstop mode specified
  1937. // also does 1 extra check when a page completely loads
  1938. // selector and words - passed dow to scissors
  1939. // params - object with multiple extra parameters:
  1940. // .log - display log in the console
  1941. // .root - selector to narrow down scope to scan;
  1942. // .observe - if true then check will be performed continuously;
  1943. // Other parameters passed down to scissors.
  1944. function gardener(selector, words, params)
  1945. {
  1946. let logger = function() { return params.log ? console.log(...arguments) : null; };
  1947. params = params || {};
  1948. logger(`[gardener] selector: '${selector}' detector: ${words} options: ${JSON.stringify(params)}`);
  1949. let scope;
  1950. let globalScope = [_de];
  1951. let domLoaded = false;
  1952. let getScope = root => root ? _de.querySelectorAll(root) : globalScope;
  1953. let onevent = e => {
  1954. logger(`[gardener] cleanup on ${Object.getPrototypeOf(e)} "${e.type}"`);
  1955. for (let node of scope)
  1956. scissors(selector, words, node, params);
  1957. };
  1958. let repeater = n => {
  1959. if (!domLoaded && n) {
  1960. setTimeout(repeater, 500, n - 1);
  1961. scope = getScope(params.root);
  1962. if (!scope) // exit if the root element is not present on the page
  1963. return 0;
  1964. onevent({type: 'Repeater'});
  1965. }
  1966. };
  1967. repeater(20);
  1968. document.addEventListener(
  1969. 'DOMContentLoaded', (e) => {
  1970. domLoaded = true;
  1971. // narrow down scope to a specific element
  1972. scope = getScope(params.root);
  1973. if (!scope) // exit if the root element is not present on the page
  1974. return 0;
  1975. logger('[g] scope', scope);
  1976. // add observe mode if required
  1977. if (params.observe)
  1978. {
  1979. let params = { childList:true, subtree: true };
  1980. let observer = new MutationObserver(
  1981. function(ms)
  1982. {
  1983. for (let m of ms)
  1984. if (m.addedNodes.length)
  1985. onevent(m);
  1986. }
  1987. );
  1988. for (let node of scope)
  1989. observer.observe(node, params);
  1990. logger('[g] observer enabled');
  1991. }
  1992. onevent(e);
  1993. }, false);
  1994. // wait for a full page load to do one extra cut
  1995. win.addEventListener('load', onevent, false);
  1996. }
  1997.  
  1998. // wrap popular methods to open a new tab to catch specific behaviours
  1999. function createWindowOpenWrapper(openFunc, onClickFunc)
  2000. {
  2001. let _Document = Object.getPrototypeOf(HTMLDocument),
  2002. _createElement = _Document.prototype.createElement,
  2003. _appendChild = Element.prototype.appendChild,
  2004. fakeNative = (f) => (f.toString = () => `function ${f.name}() { [native code] }`);
  2005.  
  2006. let nt = new nullTools();
  2007. fakeNative(openFunc);
  2008.  
  2009. let parser = _createElement.call(document, 'a');
  2010. let openWhitelist = (url) => {
  2011. parser.href = url;
  2012. return parser.hostname === 'www.imdb.com' || parser.hostname === 'www.kinopoisk.ru';
  2013. };
  2014.  
  2015. let redefineOpen = (obj) => {
  2016. for (let root of [obj, obj.document, _Document.prototype]) if ('open' in root) {
  2017. let _open = root.open.bind(root);
  2018. nt.define(root, 'open', (...args) => {
  2019. if (openWhitelist(args[0])) {
  2020. console.log('Whitelisted popup:', ...args);
  2021. return _open(...args);
  2022. }
  2023. return openFunc(...args);
  2024. });
  2025. }
  2026. };
  2027. redefineOpen(win);
  2028.  
  2029. function createElement(name) {
  2030. '[native code]';
  2031. // jshint validthis:true
  2032. let el = _createElement.apply(this, arguments);
  2033. // click-dispatch check for Google Chrome and similar browsers
  2034. if (el instanceof HTMLAnchorElement)
  2035. el.addEventListener('click', onClickFunc, false);
  2036. // redefine window.open in first-party frames
  2037. if (el instanceof HTMLIFrameElement || el instanceof HTMLObjectElement)
  2038. el.addEventListener('load', (e) => {
  2039. try {
  2040. redefineOpen(e.target.contentWindow);
  2041. } catch(ignore) {}
  2042. }, false);
  2043. return el;
  2044. }
  2045. fakeNative(createElement);
  2046.  
  2047. let redefineCreateElement = (obj) => {
  2048. for (let root of [obj.document, _Document.prototype]) if ('createElement' in root)
  2049. nt.define(root, 'createElement', createElement);
  2050. };
  2051. redefineCreateElement(win);
  2052.  
  2053. // wrap window.open in newly added first-party frames
  2054. Element.prototype.appendChild = function appendChild()
  2055. {
  2056. '[native code]';
  2057. let el = _appendChild.apply(this, arguments);
  2058. if (el instanceof HTMLIFrameElement) {
  2059. try {
  2060. redefineOpen(el.contentWindow);
  2061. redefineCreateElement(el.contentWindow);
  2062. } catch(ignore) {}
  2063. }
  2064. return el;
  2065. };
  2066. fakeNative(Element.prototype.appendChild);
  2067. }
  2068.  
  2069. // Function to catch and block various methods to open a new window with 3rd-party content.
  2070. // Some advertisement networks went way past simple window.open call to circumvent default popup protection.
  2071. // This funciton blocks window.open, ability to restore original window.open from an IFRAME object,
  2072. // ability to perform an untrusted (not initiated by user) click on a link, click on a link without a parent
  2073. // node or simply a link with piece of javascript code in the HREF attribute.
  2074. function preventPopups()
  2075. {
  2076. // call sandbox-me if in iframe and not whitelisted
  2077. if (inIFrame) {
  2078. win.top.postMessage({ name: 'sandbox-me', href: win.location.href }, '*');
  2079. return;
  2080. }
  2081.  
  2082. scriptLander(() => {
  2083. let open = (...args) => {
  2084. '[native code]';
  2085. console.warn('Site attempted to open a new window', args);
  2086. if (new RegExp(`^https?://${location.hostname}/`).test(args[0])) // skip extra click in case of blocked popunder
  2087. location.assign(args[0]);
  2088. return {
  2089. document: {
  2090. write: () => {},
  2091. writeln: () => {}
  2092. }
  2093. };
  2094. };
  2095.  
  2096. let clickHandler = (e) => {
  2097. let link = e.target;
  2098. if (!link.parentNode || !e.isTrusted ||
  2099. (link.href && link.href.trim().toLowerCase().indexOf('javascript') === 0))
  2100. {
  2101. e.preventDefault();
  2102. console.warn('Blocked suspicious click event', e, 'on', e.target);
  2103. }
  2104. };
  2105.  
  2106. createWindowOpenWrapper(open, clickHandler);
  2107.  
  2108. console.log('Popup prevention enabled.');
  2109. }, nullTools, createWindowOpenWrapper);
  2110. }
  2111.  
  2112. // Helper function to close background tab if site opens itself in a new tab and then
  2113. // loads a 3rd-party page in the background one (thus performing background redirect).
  2114. function preventPopunders()
  2115. {
  2116. // create "close_me" event to call high-level window.close()
  2117. let eventName = `close_me_${Math.random().toString(36).substr(2)}`;
  2118. let callClose = () => (console.log('close call'), window.close());
  2119. window.addEventListener(eventName, callClose, true);
  2120.  
  2121. scriptLander(() => {
  2122. // get host of a provided URL with help of an anchor object
  2123. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  2124. let parseURL = document.createElement('A');
  2125. let getHost = (url) => (parseURL.href = url, parseURL.hostname);
  2126. // site went to a new tab and attempts to unload
  2127. // call for high-level close through event
  2128. let closeWindow = () => window.dispatchEvent(new CustomEvent(eventName, {}));
  2129. // check is URL local or goes to different site
  2130. let isLocal = (url) => {
  2131. if (url === location.pathname || url === location.href)
  2132. return true; // URL points to current pathname or full address
  2133. let host = getHost(url);
  2134. let site = location.hostname;
  2135. return host !== '' && // URLs with unusual protocol may have empty 'host'
  2136. (site === host || site.endsWith(`.${host}`) || host.endsWith(`.${site}`));
  2137. };
  2138.  
  2139. let _open = window.open.bind(window);
  2140. let open = (...args) => {
  2141. '[native code]';
  2142. let url = args[0];
  2143. if (url && isLocal(url))
  2144. window.addEventListener('beforeunload', closeWindow, true);
  2145. // jshint validthis:true
  2146. return _open(...args);
  2147. };
  2148.  
  2149. let clickHandler = (e) => {
  2150. if (!e.target.parentNode || !e.isTrusted)
  2151. window.addEventListener('beforeunload', closeWindow, true);
  2152. };
  2153.  
  2154. createWindowOpenWrapper(open, clickHandler);
  2155.  
  2156. console.log("Background redirect prevention enabled.");
  2157. }, `let eventName="${eventName}"`, nullTools, createWindowOpenWrapper);
  2158. }
  2159.  
  2160. // Mix between check for popups and popunders
  2161. // Significantly more agressive than both and can't be used as universal solution
  2162. function preventPopMix()
  2163. {
  2164. if (inIFrame)
  2165. {
  2166. win.top.postMessage({ name: 'sandbox-me', href: win.location.href }, '*');
  2167. return;
  2168. }
  2169.  
  2170. // create "close_me" event to call high-level window.close()
  2171. let eventName = `close_me_${Math.random().toString(36).substr(2)}`;
  2172. let callClose = () => (console.log('close call'), window.close());
  2173. window.addEventListener(eventName, callClose, true);
  2174.  
  2175. scriptLander(() => {
  2176. let _open = window.open,
  2177. parseURL = document.createElement('A');
  2178. // get host of a provided URL with help of an anchor object
  2179. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  2180. let getHost = (url) => (parseURL.href = url, parseURL.host);
  2181. // site went to a new tab and attempts to unload
  2182. // call for high-level close through event
  2183. let closeWindow = () => (_open(window.location,'_self'), window.dispatchEvent(new CustomEvent(eventName, {})));
  2184. // check is URL local or goes to different site
  2185. function isLocal(url)
  2186. {
  2187. let loc = window.location;
  2188. if (url === loc.pathname || url === loc.href)
  2189. return true; // URL points to current pathname or full address
  2190. let host = getHost(url),
  2191. site = loc.host;
  2192. if (host === '')
  2193. return false; // URLs with unusual protocol may have empty 'host'
  2194. if (host.length > site.length)
  2195. [site, host] = [host, site];
  2196. return site.includes(host, site.length - host.length);
  2197. }
  2198.  
  2199. // add check for redirect for 5 seconds, then disable it
  2200. function checkRedirect()
  2201. {
  2202. window.addEventListener('beforeunload', closeWindow, true);
  2203. setTimeout(closeWindow=>window.removeEventListener('beforeunload', closeWindow, true), 5000, closeWindow);
  2204. }
  2205.  
  2206. function open(url, name)
  2207. {
  2208. '[native code]';
  2209. if (url && isLocal(url) && (!name || name === '_blank'))
  2210. {
  2211. console.warn('Suspicious local new window', arguments);
  2212. checkRedirect();
  2213. // jshint validthis:true
  2214. return _open.apply(this, arguments);
  2215. }
  2216. console.warn('Blocked attempt to open a new window', arguments);
  2217. return {
  2218. document: {
  2219. write: () => {},
  2220. writeln: () => {}
  2221. }
  2222. };
  2223. }
  2224.  
  2225. function clickHandler(e)
  2226. {
  2227. let link = e.target,
  2228. url = link.href||'';
  2229. if (e.targetParentNode && e.isTrusted || link.target !== '_blank')
  2230. {
  2231. console.log('Link', link, 'were created dinamically, but looks fine.');
  2232. return true;
  2233. }
  2234. if (isLocal(url) && link.target === '_blank')
  2235. {
  2236. console.log('Suspicious local link', link);
  2237. checkRedirect();
  2238. return;
  2239. }
  2240. console.log('Blocked suspicious click on a link', link);
  2241. e.stopPropagation();
  2242. e.preventDefault();
  2243. }
  2244.  
  2245. createWindowOpenWrapper(open, clickHandler);
  2246.  
  2247. console.log("Mixed popups prevention enabled.");
  2248. }, `let eventName="${eventName}"`, createWindowOpenWrapper);
  2249. }
  2250. // External listener for case when site known to open popups were loaded in iframe
  2251. // It will sandbox any iframe which will send message 'forbid.popups' (preventPopups sends it)
  2252. // Some sites replace frame's window.location with data-url to run in clean context
  2253. if (!inIFrame)
  2254. {
  2255. window.addEventListener(
  2256. 'message', function(e)
  2257. {
  2258. if (!e.data || e.data.name !== 'sandbox-me' || !e.data.href)
  2259. return;
  2260. let src = e.data.href;
  2261. for (let frame of document.querySelectorAll('iframe'))
  2262. if (frame.contentWindow === e.source)
  2263. {
  2264. if (frame.hasAttribute('sandbox'))
  2265. {
  2266. if (!frame.sandbox.contains('allow-popups'))
  2267. return; // exit frame since it's already sandboxed and popups are blocked
  2268. // remove allow-popups if frame already sandboxed
  2269. frame.sandbox.remove('allow-popups');
  2270. } else {
  2271. // set sandbox mode for troublesome frame and allow scripts, forms and a few other actions
  2272. // technically allowing both scripts and same-origin allows removal of the sandbox attribute,
  2273. // but to apply content must be reloaded and this script will re-apply it in the result
  2274. frame.setAttribute('sandbox','allow-forms allow-scripts allow-presentation allow-top-navigation allow-same-origin');
  2275. }
  2276. console.log('Disallowed popups from iframe', frame);
  2277.  
  2278. // reload frame content to apply restrictions
  2279. if (!src) {
  2280. src = frame.src;
  2281. console.log('Unable to get current iframe location, reloading from src', src);
  2282. } else
  2283. console.log('Reloading iframe with URL', src);
  2284. frame.src = 'about:blank';
  2285. frame.src = src;
  2286. }
  2287. }, false
  2288. );
  2289. }
  2290.  
  2291. function selectiveEval() {
  2292. scriptLander(() => {
  2293. let nt = new nullTools();
  2294. let _eval = win.eval.bind(window);
  2295. nt.define(win, 'eval', function(...args) {
  2296. if (/_0x|location\s*?=|location.href\s*?=|location.assign\(|open\(/i.test(args[0])) {
  2297. console.log(`Skipped eval of ${args[0].slice(0, 512)}\u2026`);
  2298. return null;
  2299. }
  2300. return _eval(...args);
  2301. });
  2302. }, nullTools);
  2303. }
  2304.  
  2305. // === Scripts for specific domains ===
  2306.  
  2307. let scripts = {};
  2308. // prevent popups and redirects block
  2309. // Popups
  2310. scripts.preventPopups = {
  2311. other: [
  2312. 'biqle.ru',
  2313. 'chaturbate.com',
  2314. 'dfiles.ru',
  2315. 'hentaiz.org',
  2316. 'mirrorcreator.com',
  2317. 'online-multy.ru',
  2318. 'radikal.ru', 'rumedia.ws',
  2319. 'seedoff.cc', 'seedoff.tv',
  2320. 'thepiratebay.org', 'torseed.net',
  2321. 'unionpeer.com',
  2322. 'zippyshare.com'
  2323. ],
  2324. now: preventPopups
  2325. };
  2326. // Popunders (background redirect)
  2327. scripts.preventPopunders = {
  2328. other: [
  2329. 'lostfilm-online.ru',
  2330. 'mediafire.com', 'megapeer.org', 'megapeer.ru',
  2331. 'perfectgirls.net'
  2332. ],
  2333. now: preventPopunders
  2334. };
  2335. // PopMix (both types of popups encountered on site)
  2336. scripts['openload.co'] = {
  2337. other: ['oload.tv', 'oload.info'],
  2338. now: () => {
  2339. let nt = new nullTools();
  2340. nt.define(win, 'CNight', win.CoinHive);
  2341. if (location.pathname.startsWith('/embed/'))
  2342. {
  2343. nt.define(win, 'BetterJsPop', {
  2344. add: ((a, b) => console.warn('BetterJsPop.add', a, b)),
  2345. config: ((o) => console.warn('BetterJsPop.config', o)),
  2346. Browser: { isChrome: true }
  2347. });
  2348. nt.define(win, 'isSandboxed', nt.func(null));
  2349. nt.define(win, 'adblock', false);
  2350. nt.define(win, 'adblock2', false);
  2351. } else
  2352. preventPopMix();
  2353. }
  2354. };
  2355. scripts['turbobit.net'] = preventPopMix;
  2356.  
  2357. // workaround for moradu.com/apu.php load error handler script, not sure which ad network is this
  2358. scripts['tapochek.net'] = () => {
  2359. let _appendChild = Object.getOwnPropertyDescriptor(Node.prototype, 'appendChild');
  2360. let _appendChild_value = _appendChild.value;
  2361. _appendChild.value = function appendChild(node) {
  2362. if (this === win.document.body)
  2363. if ((node instanceof HTMLScriptElement || node instanceof HTMLStyleElement) &&
  2364. /^https?:\/\/[0-9a-f]{15}\.com\/\d+(\/|\.css)$/.test(node.src) ||
  2365. node instanceof HTMLDivElement && node.style.zIndex > 900000 &&
  2366. node.style.backgroundImage.includes('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'))
  2367. throw '...eenope!';
  2368. return _appendChild_value.apply(this, arguments);
  2369. };
  2370. Object.defineProperty(Node.prototype, 'appendChild', _appendChild);
  2371.  
  2372. preventPopups();
  2373. };
  2374.  
  2375. // scripts['lostfilm-online.ru'] = () => scriptLander(() => {
  2376. //
  2377. // });
  2378.  
  2379. scripts['rustorka.com'] = {
  2380. other: ['rustorka.lib'],
  2381. dom: () => scriptLander(() => {
  2382. let link = void 0;
  2383. document.body.addEventListener('mousedown', e => {
  2384. link = e.target.closest('a, select');
  2385. }, false);
  2386. let _open = window.open.bind(window);
  2387. let _getAttribute = Element.prototype.getAttribute;
  2388. win.open = (...args) => {
  2389. let url = args[0];
  2390. let allow = false;
  2391. if (link instanceof HTMLAnchorElement) {
  2392. // third-party post links
  2393. let href = _getAttribute.call(link, 'href');
  2394. if (link.classList.contains('postLink') &&
  2395. !link.matches(`a[href*="${location.hostname}"]`) &&
  2396. (href === url || link.href === url)) {
  2397. return _open(...args);
  2398. }
  2399. // onclick # links
  2400. if (href === '#' && /window\.open/.test(_getAttribute.call(link, 'onclick'))) {
  2401. return _open(...args);
  2402. }
  2403. // force local links to load in the current window
  2404. if (href.includes(`//${location.hostname}/`))
  2405. location.assign(href);
  2406. }
  2407. // list of image hostings under upload picture button (new comment)
  2408. if (link instanceof HTMLSelectElement &&
  2409. !url.includes(location.hostname) &&
  2410. link.value === url) {
  2411. return _open(...args);
  2412. }
  2413. // looks like tabunder
  2414. if (link === null && url === location.href)
  2415. location.replace(url); // reload current page
  2416. // other cases
  2417. console.warn(`Site attempted to open "${url}" in a new window. Source: `, link);
  2418. return {};
  2419. };
  2420. })
  2421. };
  2422.  
  2423. // other
  2424. scripts['1tv.ru'] = () => scriptLander(() => {
  2425. let nt = new nullTools();
  2426. nt.define(win, 'EUMPAntiblockConfig', nt.proxy({url: '//www.1tv.ru/favicon.ico'}));
  2427. let _EUMPConfig = void 0;
  2428. let disablePlugins = {
  2429. 'antiblock': false,
  2430. 'stat1tv': false
  2431. };
  2432. Object.defineProperty(win, 'EUMPConfig', {
  2433. enumerable: true,
  2434. get: x => _EUMPConfig,
  2435. set: x => {
  2436. let plugins = x.plugins;
  2437. if (plugins) {
  2438. let id;
  2439. for (let plugin in disablePlugins) {
  2440. id = plugins.indexOf(plugin);
  2441. if (id > -1) {
  2442. plugins.splice(id, 1);
  2443. disablePlugins[plugin] = true;
  2444. }
  2445. }
  2446. console.warn(`Player plugins: active [${plugins}], disabled [${Object.keys(disablePlugins).filter(x => disablePlugins[x])}]`);
  2447. }
  2448. _EUMPConfig = x;
  2449. }
  2450. });
  2451. }, nullTools);
  2452.  
  2453. scripts['2picsun.ru'] = {
  2454. other: [
  2455. 'pics2sun.ru', '3pics-img.ru'
  2456. ],
  2457. now: () => {
  2458. Object.defineProperty(navigator, 'userAgent', {value: 'googlebot'});
  2459. }
  2460. };
  2461.  
  2462. scripts['4pda.ru'] = {
  2463. now: () => {
  2464. // https://greasyfork.org/en/scripts/14470-4pda-unbrender
  2465. let hStyle,
  2466. isForum = document.location.href.search('/forum/') !== -1,
  2467. remove = (node) => (node ? node.parentNode.removeChild(node) : null),
  2468. afterClean = () => remove(hStyle);
  2469.  
  2470. function beforeClean()
  2471. {
  2472. // attach styles before document displayed
  2473. hStyle = createStyle([
  2474. 'html { overflow-y: scroll }',
  2475. 'article + aside * { display: none !important }',
  2476. `section[id] {${(
  2477. 'position: absolute;'+
  2478. 'width: 100%'
  2479. )}}`,
  2480. `#header + div:after {${(
  2481. 'content: "";'+
  2482. 'position: fixed;'+
  2483. 'top: 0;'+
  2484. 'left: 0;'+
  2485. 'width: 100%;'+
  2486. 'height: 100%;'+
  2487. 'background-color: #E6E7E9'
  2488. )}}`,
  2489. // http://codepen.io/Beaugust/pen/DByiE
  2490. '@keyframes spin { 100% { transform: rotate(360deg) } }',
  2491. `article + aside:after {${(
  2492. 'content: "";'+
  2493. 'position: absolute;'+
  2494. 'width: 150px;'+
  2495. 'height: 150px;'+
  2496. 'top: 150px;'+
  2497. 'left: 50%;'+
  2498. 'margin-top: -75px;'+
  2499. 'margin-left: -75px;'+
  2500. 'box-sizing: border-box;'+
  2501. 'border-radius: 100%;'+
  2502. 'border: 10px solid rgba(0, 0, 0, 0.2);'+
  2503. 'border-top-color: rgba(0, 0, 0, 0.6);'+
  2504. 'animation: spin 2s infinite linear'
  2505. )}}`
  2506. ], {id:'ubrHider'}, true);
  2507.  
  2508. // display content of a page if time to load a page is more than 2 seconds to avoid
  2509. // blocking access to a page if it is loading for too long or stuck in a loading state
  2510. setTimeout(2000, afterClean);
  2511. }
  2512.  
  2513. createStyle([
  2514. '#nav .use-ad { display: block !important }',
  2515. 'article:not(.post) + article:not(#id),'+
  2516. 'html:not(#id)>body:not(#id) a[target="_blank"] img[height="90"] { display: none !important }'
  2517. ]);
  2518.  
  2519. if (!isForum)
  2520. beforeClean();
  2521.  
  2522. // save links to non-overridden functions to use later
  2523. let protectedElems;
  2524. // protect/hide changed attributes in case site attempt to restore them
  2525. function styleProtector(eventMode)
  2526. {
  2527. let _toLowerCase = String.prototype.toLowerCase,
  2528. isStyleText = (t) => (_toLowerCase.call(t) === 'style'),
  2529. protectedElems = new WeakMap();
  2530. function protoOverride(element, functionName, isStyleCheck, returnIfProtected)
  2531. {
  2532. let originalFunction = element.prototype[functionName];
  2533. element.prototype[functionName] = function wrapper()
  2534. {
  2535. if (protectedElems.has(this) && isStyleCheck(arguments[0]))
  2536. return returnIfProtected(this, arguments);
  2537. return originalFunction.apply(this, arguments);
  2538. };
  2539. }
  2540. protoOverride(Element, 'removeAttribute', isStyleText, () => undefined);
  2541. protoOverride(Element, 'hasAttribute', isStyleText, (_this) => protectedElems.get(_this) !== null);
  2542. protoOverride(Element, 'setAttribute', isStyleText, (_this, args) => protectedElems.set(_this, args[1]));
  2543. protoOverride(Element, 'getAttribute', isStyleText, (_this) => protectedElems.get(_this));
  2544. if (!eventMode)
  2545. return protectedElems;
  2546. else
  2547. {
  2548. let e = document.createEvent('Event');
  2549. e.initEvent('protoOverride', false, false);
  2550. window.protectedElems = protectedElems;
  2551. window.dispatchEvent(e);
  2552. }
  2553. }
  2554. if (!isFirefox)
  2555. protectedElems = styleProtector(false);
  2556. else
  2557. {
  2558. let script = document.createElement('script');
  2559. script.textContent = `(${styleProtector.toString()})(true);`;
  2560. window.addEventListener(
  2561. 'protoOverride', function protoOverrideCallback(e)
  2562. {
  2563. if (win.protectedElems) {
  2564. protectedElems = win.protectedElems;
  2565. delete win.protectedElems;
  2566. }
  2567. document.removeEventListener('protoOverride', protoOverrideCallback, true);
  2568. }, true
  2569. );
  2570. _appendChild(script);
  2571. _removeChild(script);
  2572. }
  2573.  
  2574. // clean a page
  2575. window.addEventListener(
  2576. 'DOMContentLoaded', function()
  2577. {
  2578. let width = () => window.innerWidth || _de.clientWidth || document.body.clientWidth || 0;
  2579. let height = () => window.innerHeight || _de.clientHeight || document.body.clientHeight || 0;
  2580.  
  2581. if (isForum)
  2582. {
  2583. let si = document.querySelector('#logostrip');
  2584. if (si)
  2585. remove(si.parentNode.nextSibling);
  2586. }
  2587.  
  2588. // clear background in the download frame
  2589. if (location.pathname.startsWith('/forum/dl/')) {
  2590. let setBackground = node => _setAttribute.call(
  2591. node,
  2592. 'style', (_getAttribute.call(node, 'style') || '') +
  2593. ';background-color:#4ebaf6!important'
  2594. );
  2595. setBackground(document.body);
  2596. for (let itm of document.querySelectorAll('body > div'))
  2597. if (!itm.querySelector('.dw-fdwlink, .content') && !itm.classList.contains('footer')) {
  2598. remove(itm);
  2599. } else {
  2600. setBackground(itm);
  2601. }
  2602. }
  2603.  
  2604. if (isForum) // Do not continue if it's a forum
  2605. return;
  2606.  
  2607. {
  2608. let si = document.querySelector('#header');
  2609. if (si)
  2610. {
  2611. let rem = si.previousSibling;
  2612. while (rem)
  2613. {
  2614. si = rem.previousSibling;
  2615. remove(rem);
  2616. rem = si;
  2617. }
  2618. }
  2619. }
  2620.  
  2621. for (let itm of document.querySelectorAll('#nav li[class]'))
  2622. if (itm && itm.querySelector('a[href^="/tag/"]'))
  2623. remove(itm);
  2624.  
  2625. let style, result,
  2626. fakeStyles = new WeakMap(),
  2627. styleProxy = {
  2628. get: function(target, prop)
  2629. {
  2630. let fakeStyle = fakeStyles.get(target);
  2631. return ((prop in fakeStyle) ? fakeStyle : target)[prop];
  2632. },
  2633. set: function(target, prop, value)
  2634. {
  2635. let fakeStyle = fakeStyles.get(target);
  2636. ((prop in fakeStyle) ? fakeStyle : target)[prop] = value;
  2637. return true;
  2638. }
  2639. };
  2640. for (let itm of document.querySelectorAll('DIV, A'))
  2641. {
  2642. if (itm.tagName ==='DIV' &&
  2643. itm.offsetWidth > 0.95 * width() &&
  2644. itm.offsetHeight > 0.85 * height())
  2645. {
  2646. style = window.getComputedStyle(itm, null);
  2647. result = [];
  2648.  
  2649. if (style.backgroundImage !== 'none')
  2650. result.push('background-image:none!important');
  2651.  
  2652. if (style.backgroundColor !== 'transparent' &&
  2653. style.backgroundColor !== 'rgba(0, 0, 0, 0)')
  2654. result.push('background-color:transparent!important');
  2655.  
  2656. if (result.length)
  2657. {
  2658. if (itm.getAttribute('style'))
  2659. result.unshift(itm.getAttribute('style'));
  2660.  
  2661. fakeStyles.set(itm.style, {
  2662. 'backgroundImage': itm.style.backgroundImage,
  2663. 'backgroundColor': itm.style.backgroundColor
  2664. });
  2665.  
  2666. try {
  2667. Object.defineProperty(itm, 'style', {
  2668. value: new Proxy(itm.style, styleProxy),
  2669. enumerable: true
  2670. });
  2671. } catch (e) {
  2672. console.log('Unable to protect style property.', e);
  2673. }
  2674.  
  2675. if (protectedElems)
  2676. protectedElems.set(itm, _getAttribute.call(itm, 'style'));
  2677.  
  2678. _setAttribute.call(itm, 'style', result.join(';'));
  2679. }
  2680. }
  2681. if (itm.tagName ==='A' &&
  2682. (itm.offsetWidth > 0.95 * width() ||
  2683. itm.offsetHeight > 0.85 * height()))
  2684. {
  2685. if (protectedElems)
  2686. protectedElems.set(itm, _getAttribute.call(itm, 'style'));
  2687.  
  2688. _setAttribute.call(itm, 'style', 'display:none!important');
  2689. }
  2690. }
  2691.  
  2692. for (let itm of document.querySelectorAll('ASIDE>DIV'))
  2693. if ( ((itm.querySelector('script, iframe, a[href*="/ad/www/"]') ||
  2694. itm.querySelector('img[src$=".gif"]:not([height="0"]), img[height="400"]')) &&
  2695. !itm.classList.contains('post') ) || !itm.childNodes.length )
  2696. remove(itm);
  2697.  
  2698. document.body.setAttribute('style', (document.body.getAttribute('style')||'')+';background-color:#E6E7E9!important');
  2699.  
  2700. // display content of the page
  2701. afterClean();
  2702. }
  2703. );
  2704. }
  2705. };
  2706.  
  2707. scripts['adhands.ru'] = () => scriptLander(() => {
  2708. let nt = new nullTools();
  2709. try {
  2710. let _adv;
  2711. Object.defineProperty(win, 'adv', {
  2712. get: () => _adv,
  2713. set: (v) => {
  2714. console.log('Blocked advert on adhands.ru.');
  2715. nt.define(v, 'advert', '');
  2716. _adv = v;
  2717. }
  2718. });
  2719. } catch (ignore) {
  2720. if (!win.adv)
  2721. console.log('Unable to locate advert on adhands.ru.');
  2722. else {
  2723. console.log('Blocked advert on adhands.ru.');
  2724. nt.define(win.adv, 'advert', '');
  2725. }
  2726. }
  2727. }, nullTools);
  2728.  
  2729. scripts['allhentai.ru'] = () => {
  2730. selectiveEval();
  2731. preventPopups();
  2732. scriptLander(() => {
  2733. let _onerror = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onerror');
  2734. if (!_onerror)
  2735. return;
  2736. _onerror.set = (...args) => console.log(args[0].toString());
  2737. Object.defineProperty(HTMLElement.prototype, 'onerror', _onerror);
  2738. });
  2739. };
  2740.  
  2741. scripts['allmovie.pro'] = {
  2742. other: ['rufilmtv.org'],
  2743. dom: function()
  2744. {
  2745. // pretend to be Android to make site use different played for ads
  2746. if (isSafari)
  2747. return;
  2748. Object.defineProperty(navigator, 'userAgent', {
  2749. 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'; },
  2750. enumerable: true
  2751. });
  2752. }
  2753. };
  2754.  
  2755. scripts['anidub-online.ru'] = {
  2756. other: ['online.anidub.com'],
  2757. dom: function()
  2758. {
  2759. if (win.ogonekstart1)
  2760. win.ogonekstart1 = () => console.log("Fire in the hole!");
  2761. },
  2762. now: () => createStyle([
  2763. '.background {background: none!important;}',
  2764. '.background > script + div,'+
  2765. '.background > script ~ div:not([id]):not([class]) + div[id][class]'+
  2766. '{display:none!important}'
  2767. ])
  2768. };
  2769.  
  2770. scripts['drive2.ru'] = () => gardener('.c-block:not([data-metrika="recomm"]),.o-grid__item', />Реклама<\//i);
  2771.  
  2772. scripts['fishki.net'] = () => {
  2773. scriptLander(() => {
  2774. let nt = new nullTools();
  2775. let fishki = {};
  2776. nt.define(fishki, 'adv', nt.proxy({
  2777. afterAdblockCheck: nt.func(null),
  2778. refreshFloat: nt.func(null)
  2779. }));
  2780. nt.define(fishki, 'is_adblock', false);
  2781. nt.define(win, 'fishki', fishki);
  2782. }, nullTools);
  2783. gardener('.drag_list > .drag_element, .list-view > .paddingtop15, .post-wrap', /543769|Новости\sпартнеров|Полезная\sреклама/);
  2784. };
  2785.  
  2786. scripts['gidonline.club'] = () => createStyle('.tray > div[style] {display: none!important}');
  2787.  
  2788. scripts['hdgo.cc'] = {
  2789. other: ['46.30.43.38', 'couber.be'],
  2790. now: () => (new MutationObserver(
  2791. (ms) => {
  2792. let m, node;
  2793. for (m of ms) for (node of m.addedNodes)
  2794. if (node.tagName instanceof HTMLScriptElement && _getAttribute.call(node, 'onerror') !== null)
  2795. node.removeAttribute('onerror');
  2796. }
  2797. )).observe(document.documentElement, { childList:true, subtree: true })
  2798. };
  2799.  
  2800. scripts['gismeteo.ru'] = {
  2801. other: ['gismeteo.ua'],
  2802. now: () => gardener('div > script', /AdvManager/i, { observe: true, parent: 'div' })
  2803. };
  2804.  
  2805. scripts['hdrezka.ag'] = () => {
  2806. Object.defineProperty(win, 'ab', { value: false, enumerable: true });
  2807. gardener('div[id][onclick][onmouseup][onmousedown]', /onmouseout/i);
  2808. };
  2809.  
  2810. scripts['hideip.me'] = {
  2811. now: () => scriptLander(() => {
  2812. let _innerHTML = Object.getOwnPropertyDescriptor(Element.prototype, 'innerHTML');
  2813. let _set_innerHTML = _innerHTML.set;
  2814. let _innerText = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'innerText');
  2815. let _get_innerText = _innerText.get;
  2816. let div = document.createElement('div');
  2817. _innerHTML.set = function(...args) {
  2818. _set_innerHTML.call(div, args[0].replace('i','a'));
  2819. if (args[0] && /[рp][еe]кл/.test(_get_innerText.call(div))||
  2820. /(\d\d\d?\.){3}\d\d\d?\:\d/.test(_get_innerText.call(this)) ) {
  2821. console.log('Anti-Adblock killed.');
  2822. return true;
  2823. }
  2824. _set_innerHTML.apply(this, args);
  2825. };
  2826. Object.defineProperty(Element.prototype, 'innerHTML', _innerHTML);
  2827. Object.defineProperty(win, 'adblock', {
  2828. get: x => false,
  2829. set: x => null,
  2830. enumerable: true
  2831. });
  2832. let _$ = {};
  2833. let _$_map = new WeakMap();
  2834. let _gOPD = Object.getOwnPropertyDescriptor(Object, 'getOwnPropertyDescriptor');
  2835. let _val_gOPD = _gOPD.value;
  2836. _gOPD.value = function(...args) {
  2837. let _res = _val_gOPD.apply(this, args);
  2838. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery')) {
  2839. delete _res.get;
  2840. delete _res.set;
  2841. _res.value = win[args[1]];
  2842. }
  2843. return _res;
  2844. };
  2845. Object.defineProperty(Object, 'getOwnPropertyDescriptor', _gOPD);
  2846. let getJQWrap = (n) => {
  2847. let name = n;
  2848. return {
  2849. enumerable: true,
  2850. get: x => _$[name],
  2851. set: x => {
  2852. if (_$_map.has(x)) {
  2853. _$[name] = _$_map.get(x);
  2854. return true;
  2855. }
  2856. if (x === _$.$ || x === _$.jQuery) {
  2857. _$[name] = x;
  2858. return true;
  2859. }
  2860. _$[name] = new Proxy(x, {
  2861. apply: (t, o, args) => {
  2862. let _res = t.apply(o, args);
  2863. if (_$_map.has(_res.is)) {
  2864. _res.is = _$_map.get(_res.is);
  2865. } else {
  2866. let _is = _res.is;
  2867. _res.is = function(...args) {
  2868. if (args[0] === ':hidden')
  2869. return false;
  2870. return _is.apply(this, args);
  2871. };
  2872. _$_map.set(_is, _res.is);
  2873. }
  2874. return _res;
  2875. }
  2876. });
  2877. _$_map.set(x, _$[name]);
  2878. return true;
  2879. }
  2880. };
  2881. };
  2882. Object.defineProperty(win, '$', getJQWrap('$'));
  2883. Object.defineProperty(win, 'jQuery', getJQWrap('jQuery'));
  2884. let _dP = Object.defineProperty;
  2885. Object.defineProperty = function(...args) {
  2886. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery'))
  2887. return void 0;
  2888. return _dP.apply(this, args);
  2889. };
  2890. })
  2891. };
  2892.  
  2893. scripts['igra-prestoloff.cx'] = () => scriptLander(() => {
  2894. let nt = new nullTools();
  2895. /*jslint evil: true */ // yes, evil, I know
  2896. let _write = document.write.bind(document);
  2897. /*jslint evil: false */
  2898. nt.define(document, 'write', t => {
  2899. let id = t.match(/jwplayer\("(\w+)"\)/i);
  2900. if (id && id[1]) {
  2901. return _write(`<div id="${id[1]}"></div>${t}`);
  2902. } else {
  2903. return _write('');
  2904. }
  2905. });
  2906. });
  2907.  
  2908. scripts['imageban.ru'] = {
  2909. now: preventPopunders,
  2910. dom: () => win.addEventListener('unload', () => location.hash = 'x'+Math.random().toString(36).substr(2), true)
  2911. };
  2912.  
  2913. scripts['kinopoisk.ru'] = {
  2914. now: () => {
  2915. // set no-branding body style
  2916. createStyle('body:not(#id) { background: #d5d5d5 url(/images/noBrandBg.jpg) 50% 0 no-repeat !important }');
  2917. },
  2918. dom: () => {
  2919. (style => style ? style.parentNode.removeChild(style) : console.log('Unable to locate branding style.')
  2920. )(_de.querySelector('#branding-style'));
  2921. }
  2922. };
  2923.  
  2924. scripts['mail.ru'] = () => scriptLander(() => {
  2925. let nt = new nullTools();
  2926. // Trick to prevent mail.ru from removing 3rd-party styles
  2927. nt.define(Object.prototype, 'restoreVisibility', nt.func(null), false);
  2928. // Disable some of their counters
  2929. nt.define(win, 'rb_counter', nt.func(null, 'rb_counter'));
  2930. if (location.hostname !== 'e.mail.ru')
  2931. nt.define(win, 'createRadar', nt.func(nt.func(null, 'aRadar'), 'createRadar'));
  2932. else
  2933. nt.define(win, 'aRadar', nt.func(null, 'aRadar'));
  2934.  
  2935. // Disable page scrambler on mail.ru to let extensions easily block ads there
  2936. function defineLocator(root)
  2937. {
  2938. let _locator;
  2939. let fishnet = {
  2940. apply: (target, thisArg, args) => {
  2941. console.log(`locator.${target._name}(${JSON.stringify(args).slice(1,-1)})`);
  2942. return target.apply(thisArg, args);
  2943. }
  2944. };
  2945.  
  2946. function wrapLocator(locator)
  2947. {
  2948. if ('setup' in locator)
  2949. {
  2950. let _setup = locator.setup;
  2951. locator.setup = function(o)
  2952. {
  2953. if ('enable' in o)
  2954. {
  2955. o.enable = false;
  2956. console.log('Disable mimic mode.');
  2957. }
  2958. if ('links' in o)
  2959. {
  2960. o.links = [];
  2961. console.log('Call with empty list of sheets.');
  2962. }
  2963. return _setup.call(this, o);
  2964. };
  2965. locator.insertSheet = () => console.log('Ignore insertSheet.');
  2966. locator.wrap = () => console.log('Ignore wrap.');
  2967. }
  2968. try {
  2969. let names = [];
  2970. for (let name in locator)
  2971. if (locator[name] instanceof Function) {
  2972. locator[name]._name = name;
  2973. locator[name] = new Proxy(locator[name], fishnet);
  2974. names.push(name);
  2975. }
  2976. console.log(`[locator] wrapped properties: ${names.join(', ')}`);
  2977. } catch(e) {
  2978. console.log(e);
  2979. }
  2980. _locator = locator;
  2981. }
  2982.  
  2983. if ('locator' in root && root.locator)
  2984. {
  2985. console.log('Found existing "locator" object. :|');
  2986. _locator = root.locator;
  2987. wrapLocator(root.locator);
  2988. }
  2989.  
  2990. let loc_desc = Object.getOwnPropertyDescriptor(root, 'locator');
  2991. if (!loc_desc || loc_desc.set !== wrapLocator)
  2992. try {
  2993. Object.defineProperty(root, 'locator', {
  2994. set: wrapLocator,
  2995. get: () => _locator
  2996. });
  2997. } catch (err) {
  2998. console.log('Unable to redefine "locator" object!!!', err);
  2999. }
  3000. }
  3001.  
  3002. function defineDetector(mr)
  3003. {
  3004. let __ = mr._ || {};
  3005.  
  3006. if ('HONEYPOT' in __)
  3007. {
  3008. console.log('Disarming existing detector instance. :|', JSON.stringify(__));
  3009. nt.define(__, 'HONEYPOT', '.honeypot_fake_class_to_miss');
  3010. nt.define(__, 'STUCK_IN_POT', false);
  3011. }
  3012.  
  3013. __ = new Proxy(__, {
  3014. get: (t, p) => t[p],
  3015. set: (t, p, v) => {
  3016. console.log(`mr._.${p} =`, v);
  3017. if (['HONEYPOT', 'STUCK_IN_POT'].includes(p))
  3018. console.log('Not changed.');
  3019. t[p] = v; // setter in nt.define will prevent this when needed
  3020. return true;
  3021. }
  3022. });
  3023. Object.defineProperty(mr, '_', {
  3024. enumerable: true,
  3025. value: __
  3026. });
  3027. }
  3028.  
  3029. if (location.hostname === 'e.mail.ru')
  3030. defineLocator(win);
  3031. else {
  3032. try {
  3033. let _mr;
  3034. Object.defineProperty(win, 'mr', {
  3035. enumerable: true,
  3036. get: () => _mr,
  3037. set: (v) => {
  3038. if (v === _mr)
  3039. return true;
  3040. console.log('Trapped new "mr" object.');
  3041. defineLocator(v.mimic ? v.mimic : v);
  3042. defineDetector(v);
  3043. _mr = v;
  3044. }
  3045. });
  3046. if (!('mr' in win))
  3047. throw 'Wat!?';
  3048. } catch (e) {
  3049. console.log('Found existing "mr" object.', e instanceof TypeError ? '' : e);
  3050. defineLocator(win.mr);
  3051. defineDetector(win.mr);
  3052. }
  3053. }
  3054. }, nullTools);
  3055.  
  3056. scripts['megogo.net'] = {
  3057. now: () => {
  3058. let nt = new nullTools();
  3059. nt.define(win, 'adBlock', false);
  3060. nt.define(win, 'showAdBlockMessage', nt.func(null));
  3061. }
  3062. };
  3063.  
  3064. scripts['naruto-base.su'] = () => gardener('div[id^="entryID"],.block', /href="http.*?target="_blank"/i);
  3065.  
  3066. scripts['overclockers.ru'] = {
  3067. now: () => scriptLander(() => {
  3068. let _innerHTML = Object.getOwnPropertyDescriptor(Element.prototype, 'innerHTML');
  3069. let _set_innerHTML = _innerHTML.set;
  3070. _innerHTML.set = function() {
  3071. if (this === document.body) {
  3072. console.log('Anti-Adblock killed.');
  3073. return true;
  3074. }
  3075. _set_innerHTML.apply(this, arguments);
  3076. };
  3077. Object.defineProperty(Element.prototype, 'innerHTML', _innerHTML);
  3078. })
  3079. };
  3080. scripts['forums.overclockers.ru'] = {
  3081. now: () => {
  3082. createStyle('.needblock {position: fixed; left: -10000px}');
  3083. Object.defineProperty(win, 'adblck', {
  3084. get: () => 'no',
  3085. set: () => undefined,
  3086. enumerable: true
  3087. });
  3088. }
  3089. };
  3090.  
  3091. scripts['pb.wtf'] = {
  3092. other: ['piratbit.org', 'piratbit.ru'],
  3093. now: () => {
  3094. // line above topic content and images in the slider in the header
  3095. gardener(
  3096. 'a[href^="/exit/"], a[href^="/fxt/"], a[href$="=="]',
  3097. /img|Реклама|center/i,
  3098. { root: '.release-navbar,#page_content', observe: true, parent: 'div,tr' }
  3099. );
  3100. // ads in comments
  3101. gardener('img[data-name="PiraBo"]', /./i, {root:'#main_content .table', observe:true, parent:'tr'});
  3102. }
  3103. };
  3104.  
  3105. scripts['pikabu.ru'] = () => gardener('.story', /story__author[^>]+>ads</i, {root: '.inner_wrap', observe: true});
  3106.  
  3107. scripts['peka2.tv'] = () => {
  3108. let bodyClass = 'body--branding';
  3109. let checkNode = node => {
  3110. for (let className of node.classList)
  3111. if (className.includes('banner') || className === bodyClass) {
  3112. _removeAttribute.call(node, 'style');
  3113. node.classList.remove(className);
  3114. for (let attr of Array.from(node.attributes)) {
  3115. if (attr.name.startsWith('advert'))
  3116. _removeAttribute.call(node, attr.name);
  3117. }
  3118. }
  3119. };
  3120. (new MutationObserver(ms => {
  3121. let m, node;
  3122. for (m of ms) for (node of m.addedNodes)
  3123. if (node instanceof HTMLElement)
  3124. checkNode(node);
  3125. })).observe(_de, {childList: true, subtree: true});
  3126. (new MutationObserver(ms => {
  3127. for (let m of ms)
  3128. checkNode(m.target);
  3129. })).observe(_de, {attributes: true, subtree: true, attributeFilter: ['class']});
  3130. };
  3131.  
  3132. scripts['qrz.ru'] = {
  3133. now: () => {
  3134. let nt = new nullTools();
  3135. nt.define(win, 'ab', false);
  3136. nt.define(win, 'tryMessage', nt.func(null));
  3137. }
  3138. };
  3139.  
  3140. scripts['razlozhi.ru'] = {
  3141. now: () => {
  3142. for (let func of ['createShadowRoot', 'attachShadow'])
  3143. if (func in Element.prototype)
  3144. Element.prototype[func] = function(){ return this.cloneNode(); };
  3145. }
  3146. };
  3147.  
  3148. scripts['rbc.ru'] = {
  3149. dom: () => {
  3150. let _preventDefault = Event.prototype.preventDefault;
  3151. Event.prototype.preventDefault = function preventDefault()
  3152. {
  3153. let t = this.target;
  3154. if (t instanceof HTMLAnchorElement || t.closest('A'))
  3155. throw new Error('an.yandex redirect prevention');
  3156. return _preventDefault.call(this);
  3157. };
  3158.  
  3159. function cleaner(nodes)
  3160. {
  3161. for (let node of nodes)
  3162. {
  3163. if (!node.classList || !node.classList.contains('js-yandex-counter'))
  3164. continue;
  3165. node.classList.remove('js-yandex-counter');
  3166. node.removeAttribute('data-yandex-name');
  3167. node.removeAttribute('data-yandex-params');
  3168. }
  3169. }
  3170. cleaner(_de.querySelectorAll('.js-yandex-counter'));
  3171.  
  3172. (new MutationObserver(
  3173. ms => { for (let m of ms) cleaner(m.addedNodes); }
  3174. )).observe(_de, {childList: true, subtree: true});
  3175. }
  3176. };
  3177.  
  3178. scripts['rp5.ru'] = {
  3179. other: ['rp5.by', 'rp5.kz', 'rp5.ua'],
  3180. now: () => gardener('div[id][class]', /\?AdvertMgmt=|adsbygoogle/, { root: '#content-wrapper', log: true })
  3181. };
  3182.  
  3183. scripts['rutube.ru'] = () => scriptLander(() => {
  3184. let _parse = JSON.parse.bind(JSON);
  3185. let _skip_enabled = false;
  3186. JSON.parse = (...args) => {
  3187. let res = _parse(...args);
  3188.  
  3189. // parse player configuration
  3190. if ('advert' in res)
  3191. res.advert = [];
  3192. if ('limits' in res)
  3193. for (let limit of res.limits)
  3194. limit.limit = 0;
  3195. if ('remove_unseekable_blocks' in res)
  3196. res.remove_unseekable_blocks = true;
  3197. if (!('cuepoints' in res))
  3198. _skip_enabled = !!res.remove_unseekable_blocks;
  3199. if ('yast' in res) {
  3200. res.yast = null;
  3201. res.stat = [];
  3202. }
  3203. if ('yast_live_online' in res)
  3204. res.yast_live_online = null;
  3205.  
  3206. // parse video configuration
  3207. if ('cuepoints' in res && !_skip_enabled)
  3208. for (let point of res.cuepoints)
  3209. {
  3210. point.is_pause = false;
  3211. point.show_navigation = true;
  3212. point.forbid_seek = false;
  3213. }
  3214.  
  3215. console.log('[rutube]', res);
  3216. return res;
  3217. };
  3218. });
  3219.  
  3220. scripts['simpsonsua.com.ua'] = () => scriptLander(() => {
  3221. let _addEventListener = Object.getPrototypeOf(HTMLDocument).prototype.addEventListener;
  3222. document.addEventListener = function(event, callback) {
  3223. if (event === 'DOMContentLoaded' && callback.toString().includes('show_warning'))
  3224. return;
  3225. return _addEventListener.apply(this, arguments);
  3226. };
  3227. });
  3228.  
  3229. scripts['spaces.ru'] = () => {
  3230. gardener('div:not(.f-c_fll) > a[href*="spaces.ru/?Cl="]', /./, { parent: 'div' });
  3231. gardener('.js-banner_rotator', /./, { parent: '.widgets-group' });
  3232. };
  3233.  
  3234. scripts['spam-club.blogspot.co.uk'] = () => {
  3235. let _clientHeight = Object.getOwnPropertyDescriptor(Element.prototype, 'clientHeight'),
  3236. _clientWidth = Object.getOwnPropertyDescriptor(Element.prototype, 'clientWidth');
  3237. let wrapGetter = (getter) => {
  3238. let _getter = getter;
  3239. return function()
  3240. {
  3241. let _size = _getter.apply(this, arguments);
  3242. return _size ? _size : 1;
  3243. };
  3244. };
  3245. _clientHeight.get = wrapGetter(_clientHeight.get);
  3246. _clientWidth.get = wrapGetter(_clientWidth.get);
  3247. Object.defineProperty(Element.prototype, 'clientHeight', _clientHeight);
  3248. Object.defineProperty(Element.prototype, 'clientWidth', _clientWidth);
  3249. let _onload = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onload'),
  3250. _set_onload = _onload.set;
  3251. _onload.set = function()
  3252. {
  3253. if (this instanceof HTMLImageElement)
  3254. return true;
  3255. _set_onload.apply(this, arguments);
  3256. };
  3257. Object.defineProperty(HTMLElement.prototype, 'onload', _onload);
  3258. };
  3259.  
  3260. scripts['sport-express.ru'] = () => gardener('.js-relap__item',/>Реклама\s+<\//, {root:'.container', observe: true});
  3261.  
  3262. scripts['sports.ru'] = {
  3263. now: () => {
  3264. gardener('.aside-news-list__item', /aside-news-list__advert/i, {root:'.columns-layout__left', observe: true});
  3265. gardener('.material-list__item', /Реклама/i, {root:'.columns-layout', observe: true});
  3266. // extra functionality: shows/hides panel at the top depending on scroll direction
  3267. createStyle([
  3268. '.user-panel__fixed { transition: top 0.2s ease-in-out!important; }',
  3269. '.user-panel-up { top: -40px!important }'
  3270. ], {id: 'userPanelSlide'}, false);
  3271. },
  3272. dom: () => {
  3273. (function lookForPanel()
  3274. {
  3275. let panel = document.querySelector('.user-panel__fixed');
  3276. if (!panel)
  3277. setTimeout(lookForPanel, 100);
  3278. else
  3279. window.addEventListener(
  3280. 'wheel', function(e)
  3281. {
  3282. if (e.deltaY > 0 && !panel.classList.contains('user-panel-up'))
  3283. panel.classList.add('user-panel-up');
  3284. else if (e.deltaY < 0 && panel.classList.contains('user-panel-up'))
  3285. panel.classList.remove('user-panel-up');
  3286. }, false
  3287. );
  3288. })();
  3289. }
  3290. };
  3291.  
  3292. scripts['stealthz.ru'] = {
  3293. dom: () => {
  3294. // skip timeout
  3295. let $ = document.querySelector.bind(document);
  3296. let [timer_1, timer_2] = [$('#timer_1'), $('#timer_2')];
  3297. if (!timer_1 || !timer_2)
  3298. return;
  3299. timer_1.style.display = 'none';
  3300. timer_2.style.display = 'block';
  3301. }
  3302. };
  3303.  
  3304. scripts['yap.ru'] = {
  3305. other: ['yaplakal.com'],
  3306. now: () => {
  3307. gardener('form > table[id^="p_row_"]:nth-of-type(2)', /member1438|Administration/);
  3308. gardener('.icon-comments', /member1438|Administration|\/go\/\?http/, {parent:'tr', siblings:-2});
  3309. }
  3310. };
  3311.  
  3312. scripts['rambler.ru'] = {
  3313. other: ['championat.com','gazeta.ru','media.eagleplatform.com','lenta.ru', 'quto.ru'],
  3314. now: () => scriptLander(() => {
  3315. // Prevent autoplay
  3316. if (!('EaglePlayer' in win)) {
  3317. let _EaglePlayer = void 0;
  3318. Object.defineProperty(win, 'EaglePlayer', {
  3319. enumerable: true,
  3320. get: x => _EaglePlayer,
  3321. set: x => {
  3322. if (x === _EaglePlayer)
  3323. return true;
  3324. _EaglePlayer = x;
  3325. let _init = void 0;
  3326. Object.defineProperty(_EaglePlayer.prototype, 'init', {
  3327. enumerable: true,
  3328. set: x => _init = x,
  3329. get: function() {
  3330. let _self = this;
  3331. if (_self.options) {
  3332. Object.defineProperty(this.options, 'autoplay', {
  3333. enumerable: true,
  3334. get: x => false,
  3335. set: x => null
  3336. });
  3337. }
  3338. if (_self.options && _self.options.el && inIFrame) {
  3339. let addListener = (player) => {
  3340. console.log('Attached autostop');
  3341. player.addEventListener('canplay', e => {
  3342. e.target.play = () => console.log('Applied autostop.');
  3343. setTimeout(player => {
  3344. delete player.play;
  3345. console.log('Detached autostop');
  3346. }, 1500, e.target);
  3347. }, false);
  3348. };
  3349. (new MutationObserver(ms => {
  3350. let m, node;
  3351. for (m of ms) for (node of m.addedNodes)
  3352. if (node instanceof HTMLVideoElement)
  3353. addListener(node);
  3354. })).observe(this.options.el, { childList: true, subtree: true });
  3355. }
  3356. return _init;
  3357. }
  3358. });
  3359. }
  3360. });
  3361. let _setAttribute = Element.prototype.setAttribute;
  3362. let isAutoplay = /^autoplay$/i;
  3363. Element.prototype.setAttribute = function setAttribute(name)
  3364. {
  3365. if (!this._stopped && isAutoplay.test(name))
  3366. {
  3367. console.log('Prevented assigning autoplay attribute.');
  3368. return null;
  3369. }
  3370. return _setAttribute.apply(this, arguments);
  3371. };
  3372. } else if (inIFrame) {
  3373. let _setAttribute = Element.prototype.setAttribute;
  3374. let isAutoplay = /^autoplay$/i;
  3375. Element.prototype.setAttribute = function setAttribute(name)
  3376. {
  3377. if (!this._stopped && isAutoplay.test(name))
  3378. {
  3379. console.log('Prevented assigning autoplay attribute.');
  3380. this._stopped = true;
  3381. this.play = () => {
  3382. console.log('Prevented attempt to force-start playback.');
  3383. delete this.play;
  3384. };
  3385. return null;
  3386. }
  3387. return _setAttribute.apply(this, arguments);
  3388. };
  3389. }
  3390. if (location.hostname.endsWith('.media.eagleplatform.com'))
  3391. return;
  3392. let CSSRuleProto = 'cssText' in CSSRule.prototype ? CSSRule.prototype : CSSStyleRule.prototype;
  3393. let _cssText = Object.getOwnPropertyDescriptor(CSSRuleProto, 'cssText');
  3394. let _cssText_get = _cssText.get;
  3395. _cssText.configurable = false;
  3396. _cssText.get = function()
  3397. {
  3398. let cssText = _cssText_get.call(this);
  3399. if (cssText.includes('content:'))
  3400. {
  3401. console.log('Blocked access to suspicious cssText:', cssText.slice(0,60), '\u2026', cssText.length);
  3402. return null;
  3403. }
  3404. return cssText;
  3405. };
  3406. Object.defineProperty(CSSRuleProto, 'cssText', _cssText);
  3407. // fake global Adf object
  3408. let nt = new nullTools();
  3409. let Adf_banner = {};
  3410. [
  3411. 'reloadssp', 'sspScroll',
  3412. 'sspRich', 'ssp'
  3413. ].map(name => Adf_banner[name] = nt.proxy(() => new Promise((r,j) => r({status: true}))));
  3414. nt.define(win, 'Adf', nt.proxy({
  3415. banner: nt.proxy(Adf_banner)
  3416. }));
  3417. // extra script to remove partner news on gazeta.ru
  3418. if (!location.hostname.includes('gazeta.ru'))
  3419. return;
  3420. (new MutationObserver(
  3421. (ms) => {
  3422. let m, node, header;
  3423. for (m of ms) for (node of m.addedNodes)
  3424. if (node instanceof HTMLDivElement && node.matches('.sausage'))
  3425. {
  3426. header = node.querySelector('.sausage-header');
  3427. if (header && /новости\s+партн[её]ров/i.test(header.textContent))
  3428. node.style.display = 'none';
  3429. }
  3430. }
  3431. )).observe(document.documentElement, { childList:true, subtree: true });
  3432. }, `let inIFrame = ${inIFrame}`, nullTools)
  3433. };
  3434.  
  3435. scripts['reactor.cc'] = {
  3436. other: ['joyreactor.cc', 'pornreactor.cc'],
  3437. now: () => {
  3438. selectiveEval();
  3439. scriptLander(() => {
  3440. let nt = new nullTools();
  3441. win.open = (function(){ throw new Error('Redirect prevention.'); }).bind(window);
  3442. nt.define(win, 'Worker', function(){});
  3443. nt.define(win, 'JRCH', win.CoinHive);
  3444. }, nullTools);
  3445. },
  3446. click: function(e)
  3447. {
  3448. let node = e.target;
  3449. if (node.nodeType === Node.ELEMENT_NODE &&
  3450. node.style.position === 'absolute' &&
  3451. node.style.zIndex > 0)
  3452. node.parentNode.removeChild(node);
  3453. },
  3454. dom: function()
  3455. {
  3456. let words = new RegExp(
  3457. 'блокировщик рекламы'
  3458. .split('')
  3459. .map(function(e){return e+'[\u200b\u200c\u200d]*';})
  3460. .join('')
  3461. .replace(' ', '\\s*')
  3462. .replace(/[аоре]/g, function(e){return ['[аa]','[оo]','[рp]','[еe]']['аоре'.indexOf(e)];}),
  3463. 'i'),
  3464. can;
  3465. function deeper(spider)
  3466. {
  3467. let c, l, n;
  3468. if (words.test(spider.innerText))
  3469. {
  3470. if (spider.nodeType === Node.TEXT_NODE)
  3471. return true;
  3472. c = spider.childNodes;
  3473. l = c.length;
  3474. n = 0;
  3475. while(l--)
  3476. if (deeper(c[l]), can)
  3477. n++;
  3478. if (n > 0 && n === c.length && spider.offsetHeight < 750)
  3479. can.push(spider);
  3480. return false;
  3481. }
  3482. return true;
  3483. }
  3484. function probe()
  3485. {
  3486. if (words.test(document.body.innerText))
  3487. {
  3488. can = [];
  3489. deeper(document.body);
  3490. let i = can.length, spider;
  3491. while(i--) {
  3492. spider = can[i];
  3493. if (spider.offsetHeight > 10 && spider.offsetHeight < 750)
  3494. _setAttribute.call(spider, 'style', 'background:none!important');
  3495. }
  3496. }
  3497. }
  3498. (new MutationObserver(probe))
  3499. .observe(document, { childList:true, subtree:true });
  3500. }
  3501. };
  3502.  
  3503. scripts['auto.ru'] = () => {
  3504. let words = /Реклама|Яндекс.Директ|yandex_ad_/;
  3505. let userAdsListAds = (
  3506. '.listing-list > .listing-item,'+
  3507. '.listing-item_type_fixed.listing-item'
  3508. );
  3509. let catalogAds = (
  3510. 'div[class*="layout_catalog-inline"],'+
  3511. 'div[class$="layout_horizontal"]'
  3512. );
  3513. let otherAds = (
  3514. '.advt_auto,'+
  3515. '.sidebar-block,'+
  3516. '.pager-listing + div[class],'+
  3517. '.card > div[class][style],'+
  3518. '.sidebar > div[class],'+
  3519. '.main-page__section + div[class],'+
  3520. '.listing > tbody'
  3521. );
  3522. gardener(userAdsListAds, words, {root:'.listing-wrap', observe:true});
  3523. gardener(catalogAds, words, {root:'.catalog__page,.content__wrapper', observe:true});
  3524. gardener(otherAds, words);
  3525. };
  3526.  
  3527. scripts['rsload.net'] = {
  3528. load: () => {
  3529. let dis = document.querySelector('label[class*="cb-disable"]');
  3530. if (dis)
  3531. dis.click();
  3532. },
  3533. click: () => {
  3534. let t = e.target;
  3535. if (t && t.href && (/:\/\/\d+\.\d+\.\d+\.\d+\//.test(t.href)))
  3536. t.href = t.href.replace('://','://rsload.net:rsload.net@');
  3537. }
  3538. };
  3539.  
  3540. let domain;
  3541. // add alternative domain names if present and wrap functions into objects
  3542. for (let name in scripts)
  3543. {
  3544. if (scripts[name] instanceof Function)
  3545. scripts[name] = { now: scripts[name] };
  3546. for (domain of (scripts[name].other||[]))
  3547. {
  3548. if (domain in scripts)
  3549. console.log('Error in scripts list. Script for', name, 'replaced script for', domain);
  3550. scripts[domain] = scripts[name];
  3551. }
  3552. delete scripts[name].other;
  3553. }
  3554. // look for current domain in the list and run appropriate code
  3555. domain = document.domain;
  3556. while (domain.indexOf('.') > -1)
  3557. {
  3558. if (domain in scripts) for (let when in scripts[domain])
  3559. switch(when)
  3560. {
  3561. case 'now':
  3562. scripts[domain][when]();
  3563. break;
  3564. case 'dom':
  3565. document.addEventListener('DOMContentLoaded', scripts[domain][when], false);
  3566. break;
  3567. default:
  3568. document.addEventListener (when, scripts[domain][when], false);
  3569. }
  3570. domain = domain.slice(domain.indexOf('.') + 1);
  3571. }
  3572. })();