RU AdList JS Fixes

try to take over the world!

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

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