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