RU AdList JS Fixes

try to take over the world!

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

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