RU AdList JS Fixes

try to take over the world!

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

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