RU AdList JS Fixes

try to take over the world!

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

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