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