RU AdList JS Fixes

try to take over the world!

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

  1. // ==UserScript==
  2. // @name RU AdList JS Fixes
  3. // @namespace ruadlist_js_fixes
  4. // @version 20180218.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', 'sendTTI',
  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. let AwapsJsonAPI_Json = function(...args) {
  1659. console.log('>> new AwapsJsonAPI.Json(', ...args, ')');
  1660. };
  1661. [
  1662. 'setID', 'addImageContent',
  1663. 'sendCounts', 'expand', 'refreshAd'
  1664. ].map(name => AwapsJsonAPI_Json.prototype[name] = nt.proxy(nt.func(null, name)));
  1665. AwapsJsonAPI_Json.prototype.checkBannerVisibility = nt.proxy(nt.func(true, 'checkBannerVisibility'));
  1666. AwapsJsonAPI_Json.prototype.addIframeContent = nt.proxy(function(...args) {
  1667. try {
  1668. let frame = args[1][0].parentNode;
  1669. frame.parentNode.removeChild(frame);
  1670. console.log(`Removed banner placeholder.`);
  1671. } catch(ignore) {
  1672. console.log(`Can't locate frame object to remove.`);
  1673. }
  1674. });
  1675. AwapsJsonAPI_Json.prototype.getHTML = nt.proxy(nt.func('', 'getHTML'));
  1676. AwapsJsonAPI_Json.prototype = nt.proxy(AwapsJsonAPI_Json.prototype);
  1677. AwapsJsonAPI_Json = nt.proxy(AwapsJsonAPI_Json);
  1678. if ('AwapsJsonAPI' in win) {
  1679. console.log('Oops! AwapsJsonAPI already defined.');
  1680. let f = win.AwapsJsonAPI.Json;
  1681. win.AwapsJsonAPI.Json = AwapsJsonAPI_Json;
  1682. if (f && f.prototype)
  1683. f.prototype = AwapsJsonAPI_Json.prototype;
  1684. } else {
  1685. nt.define(win, 'AwapsJsonAPI', nt.proxy({
  1686. Json: AwapsJsonAPI_Json
  1687. }));
  1688. }
  1689.  
  1690. let home = win.home || {};
  1691. let parseExport = x => {
  1692. if (!x)
  1693. return x;
  1694. // remove banner placeholder
  1695. if (x.banner && x.banner.cls) {
  1696. let _parent = `.${x.banner.cls.banner__parent}`;
  1697. document.addEventListener('DOMContentLoaded', () => {
  1698. for (let banner of document.querySelectorAll(_parent)) {
  1699. _setAttribute.call(banner, 'style', 'display:none!important');
  1700. console.log('Hid banner placeholder.');
  1701. }
  1702. }, false);
  1703. }
  1704.  
  1705. // remove banner data and some other stuff
  1706. delete x.banner;
  1707. delete x.consistency;
  1708. delete x['i-bannerid'];
  1709. delete x['i-counter'];
  1710. delete x['ga-counter'];
  1711. delete x['promo-curtain'];
  1712.  
  1713. return x;
  1714. };
  1715. let home_export = parseExport(home.export);
  1716. Object.defineProperty(home, 'export', {
  1717. get: x => home_export,
  1718. set: x => {
  1719. home_export = parseExport(x);
  1720. }
  1721. });
  1722. nt.define(win, 'home', home);
  1723. }, nullTools, '_setAttribute = Element.prototype.setAttribute');
  1724.  
  1725. if ('attachShadow' in Element.prototype) {
  1726. let fakeRoot = () => ({
  1727. firstChild: null,
  1728. appendChild: ()=>null,
  1729. querySelector: ()=>null,
  1730. querySelectorAll: ()=>null
  1731. });
  1732. Element.prototype.createShadowRoot = fakeRoot;
  1733. let shadows = new WeakMap();
  1734. let _attachShadow = Object.getOwnPropertyDescriptor(Element.prototype, 'attachShadow');
  1735. let _call_attachShadow = _attachShadow.value;
  1736. _attachShadow.value = function() {
  1737. return shadows.set(this, fakeRoot()).get(this);
  1738. };
  1739. Object.defineProperty(Element.prototype, 'attachShadow', _attachShadow);
  1740. let _shadowRoot = Object.getOwnPropertyDescriptor(Element.prototype, 'shadowRoot');
  1741. _shadowRoot.set = () => null;
  1742. _shadowRoot.get = function() {
  1743. return shadows.has(this) ? shadows.get(this) : void 0;
  1744. };
  1745. Object.defineProperty(Element.prototype, 'shadowRoot', _shadowRoot);
  1746. }
  1747. // Partially based on https://greasyfork.org/en/scripts/22737-remove-yandex-redirect
  1748. let selectors = (
  1749. 'A[onmousedown*="/jsredir"],'+
  1750. 'A[data-vdir-href],'+
  1751. 'A[data-counter]'
  1752. );
  1753. let removeTrackingAttributes = function(link)
  1754. {
  1755. link.removeAttribute('onmousedown');
  1756. if (link.hasAttribute('data-vdir-href')) {
  1757. link.removeAttribute('data-vdir-href');
  1758. link.removeAttribute('data-orig-href');
  1759. }
  1760. if (link.hasAttribute('data-counter')) {
  1761. link.removeAttribute('data-counter');
  1762. link.removeAttribute('data-bem');
  1763. }
  1764. };
  1765. let removeTracking = function(scope)
  1766. {
  1767. for (let link of scope.querySelectorAll(selectors))
  1768. removeTrackingAttributes(link);
  1769. };
  1770. document.addEventListener('DOMContentLoaded', (e) => removeTracking(e.target));
  1771. (new MutationObserver(
  1772. function(ms)
  1773. {
  1774. let m, node;
  1775. for (m of ms) for (node of m.addedNodes) if (node.nodeType === Node.ELEMENT_NODE)
  1776. if (node.tagName === 'A' && node.matches(selectors)) {
  1777. removeTrackingAttributes(node);
  1778. } else {
  1779. removeTracking(node);
  1780. }
  1781. }
  1782. )).observe(_de, { childList: true, subtree: true });
  1783.  
  1784. //skip fixes for other sites
  1785. return;
  1786. }
  1787.  
  1788. // https://greasyfork.org/en/scripts/21937-moonwalk-hdgo-kodik-fix v0.8 (adapted)
  1789. document.addEventListener(
  1790. 'DOMContentLoaded', function()
  1791. {//createPlayer();
  1792. function log (name) {
  1793. console.log(`Player FIX: Detected ${name} player in ${location.href}`);
  1794. }
  1795. if (win.adv_enabled !== undefined && win.condition_detected !== undefined)
  1796. {
  1797. log('Moonwalk');
  1798. if (win.adv_enabled)
  1799. win.adv_enabled = false;
  1800. win.condition_detected = false;
  1801. if (win.MXoverrollCallback)
  1802. document.addEventListener(
  1803. 'click', function catcher(e)
  1804. {
  1805. e.stopPropagation();
  1806. win.MXoverrollCallback.call(window);
  1807. document.removeEventListener('click', catcher, true);
  1808. }, true
  1809. );
  1810. }
  1811. else if (win.stat_url !== undefined && win.is_html5 !== undefined && win.is_wp8 !== undefined)
  1812. {
  1813. log('HDGo');
  1814. document.body.onclick = null;
  1815. let tmp = document.querySelector('#swtf');
  1816. if (tmp)
  1817. tmp.style.display = 'none';
  1818. if (win.banner_second !== undefined)
  1819. win.banner_second = 0;
  1820. if (win.$banner_ads !== undefined)
  1821. win.$banner_ads = false;
  1822. if (win.$new_ads !== undefined)
  1823. win.$new_ads = false;
  1824. if (win.createCookie !== undefined)
  1825. win.createCookie('popup', 'true', '999');
  1826. if (win.canRunAds !== undefined && win.canRunAds !== true)
  1827. win.canRunAds = true;
  1828. }
  1829. else if (win.MXoverrollCallback && win.iframeSearch !== undefined)
  1830. {
  1831. log('Kodik');
  1832. let tmp = document.querySelector('.play_button');
  1833. if (tmp)
  1834. tmp.onclick = win.MXoverrollCallback.bind(window);
  1835. win.IsAdBlock = false;
  1836. }
  1837. else if (win.getnextepisode && win.uppodEvent)
  1838. {
  1839. log('Share-Serials.net');
  1840. scriptLander(
  1841. function()
  1842. {
  1843. let _setInterval = win.setInterval,
  1844. _setTimeout = win.setTimeout;
  1845. win.setInterval = function(func)
  1846. {
  1847. if (func instanceof Function && func.toString().indexOf('_delay') > -1)
  1848. {
  1849. let intv = _setInterval.call(
  1850. this, function()
  1851. {
  1852. _setTimeout.call(
  1853. this, function(intv)
  1854. {
  1855. clearInterval(intv);
  1856. let timer = document.querySelector('#timer');
  1857. if (timer)
  1858. timer.click();
  1859. }, 100, intv);
  1860. func.call(this);
  1861. }, 5
  1862. );
  1863.  
  1864. return intv;
  1865. }
  1866. return _setInterval.apply(this, arguments);
  1867. };
  1868. win.setTimeout = function(func) {
  1869. if (func instanceof Function && func.toString().indexOf('adv_showed') > -1)
  1870. {
  1871. return _setTimeout.call(this, func, 0);
  1872. }
  1873. return _setTimeout.apply(this, arguments);
  1874. };
  1875. }
  1876. );
  1877. } else if ('ADC' in win)
  1878. {
  1879. log('vjs-creatives plugin in');
  1880. let replacer = (obj) => {
  1881. for (let name in obj)
  1882. if (obj[name] instanceof Function)
  1883. obj[name] = () => null;
  1884. };
  1885. replacer(win.ADC);
  1886. replacer(win.currentAdSlot);
  1887. }
  1888. UberVK: {
  1889. if (!inIFrame)
  1890. break UberVK;
  1891. let oddNames = 'HD' in win &&
  1892. !Object.getOwnPropertyNames(win).every(n => !n.startsWith('_0x'));
  1893. if (!oddNames)
  1894. break UberVK;
  1895. log('UberVK');
  1896. XMLHttpRequest.prototype.open = () => { throw 404; };
  1897. }
  1898. }, false
  1899. );
  1900.  
  1901. // piguiqproxy.com circumvention prevention
  1902. scriptLander(
  1903. () => {
  1904. let _open = XMLHttpRequest.prototype.open;
  1905. // blacklist of third-party domains requests to which are ignored
  1906. let blacklist = /[/.@](amgload\.net|dsn-fishki\.ru|piguiqproxy\.com|rcdn\.pro)[:/]/i;
  1907. // blacklist of domains where all third-party requests are ignored
  1908. let ondomains = /(^|[/.@])oane\.ws($|[:/])/i;
  1909. // highly suspicious URLs
  1910. let suspicious = /^https?:\/\/[a-z0-9]{6}\.ru\/([a-z0-9\/]{45,}|[a-z0-9]{8,}|ad\/banner\/.+)$/i;
  1911.  
  1912. XMLHttpRequest.prototype.open = function(method, url)
  1913. {
  1914. if (method === 'GET' &&
  1915. (blacklist.test(url) || suspicious.test(url) ||
  1916. ondomains.test(location.hostname) && !ondomains.test(url)))
  1917. {
  1918. this.send = () => null;
  1919. this.setRequestHeader = () => null;
  1920. console.log('Blocked request: ', url);
  1921. return;
  1922. }
  1923. return _open.apply(this, arguments);
  1924. };
  1925. }
  1926. );
  1927.  
  1928. // === Helper functions ===
  1929.  
  1930. // function to search and remove nodes by content
  1931. // selector - standard CSS selector to define set of nodes to check
  1932. // words - regular expression to check content of the suspicious nodes
  1933. // params - object with multiple extra parameters:
  1934. // .log - display log in the console
  1935. // .hide - set display to none instead of removing from the page
  1936. // .parent - parent node to remove if content is found in the child node
  1937. // .siblings - number of simling nodes to remove (excluding text nodes)
  1938. let scRemove = (node) => node.parentNode.removeChild(node);
  1939. let scHide = function(node)
  1940. {
  1941. let style = _getAttribute.call(node, 'style') || '',
  1942. hide = ';display:none!important;';
  1943. if (style.indexOf(hide) < 0)
  1944. _setAttribute.call(node, 'style', style + hide);
  1945. };
  1946.  
  1947. function scissors (selector, words, scope, params)
  1948. {
  1949. let logger = function() { return params.log ? console.log(...arguments) : null; };
  1950. if (!scope.contains(document.body))
  1951. logger('[s] scope', scope);
  1952. let remFunc = (params.hide ? scHide : scRemove),
  1953. iterFunc = (params.siblings > 0 ? 'nextElementSibling' : 'previousElementSibling'),
  1954. toRemove = [],
  1955. siblings;
  1956. for (let node of scope.querySelectorAll(selector))
  1957. {
  1958. // drill up to a parent node if specified, break if not found
  1959. if (params.parent)
  1960. {
  1961. let old = node;
  1962. node = node.closest(params.parent);
  1963. if (node === null || node.contains(scope))
  1964. {
  1965. logger('[s] went out of scope with', old);
  1966. continue;
  1967. }
  1968. }
  1969. logger('[s] processing', node);
  1970. if (toRemove.includes(node))
  1971. continue;
  1972. if (words.test(node.innerHTML))
  1973. {
  1974. // skip node if already marked for removal
  1975. logger('[s] marked for removal');
  1976. toRemove.push(node);
  1977. // add multiple nodes if defined more than one sibling
  1978. siblings = Math.abs(params.siblings) || 0;
  1979. while (siblings)
  1980. {
  1981. node = node[iterFunc];
  1982. if (!node) break; // can't go any further - exit
  1983. logger('[s] adding sibling node', node);
  1984. toRemove.push(node);
  1985. siblings -= 1;
  1986. }
  1987. }
  1988. }
  1989. let toSkip = [];
  1990. for (let node of toRemove)
  1991. if (!toRemove.every(other => other === node || !node.contains(other)))
  1992. toSkip.push(node);
  1993. if (toRemove.length)
  1994. logger(`[s] proceeding with ${params.hide?'hide':'removal'} of`, toRemove, `skip`, toSkip);
  1995. for (let node of toRemove) if (!toSkip.includes(node))
  1996. remFunc(node);
  1997. }
  1998.  
  1999. // function to perform multiple checks if ads inserted with a delay
  2000. // by default does 30 checks withing a 3 seconds unless nonstop mode specified
  2001. // also does 1 extra check when a page completely loads
  2002. // selector and words - passed dow to scissors
  2003. // params - object with multiple extra parameters:
  2004. // .log - display log in the console
  2005. // .root - selector to narrow down scope to scan;
  2006. // .observe - if true then check will be performed continuously;
  2007. // Other parameters passed down to scissors.
  2008. function gardener(selector, words, params)
  2009. {
  2010. let logger = function() { return params.log ? console.log(...arguments) : null; };
  2011. params = params || {};
  2012. logger(`[gardener] selector: '${selector}' detector: ${words} options: ${JSON.stringify(params)}`);
  2013. let scope;
  2014. let globalScope = [_de];
  2015. let domLoaded = false;
  2016. let getScope = root => root ? _de.querySelectorAll(root) : globalScope;
  2017. let onevent = e => {
  2018. logger(`[gardener] cleanup on ${Object.getPrototypeOf(e)} "${e.type}"`);
  2019. for (let node of scope)
  2020. scissors(selector, words, node, params);
  2021. };
  2022. let repeater = n => {
  2023. if (!domLoaded && n) {
  2024. setTimeout(repeater, 500, n - 1);
  2025. scope = getScope(params.root);
  2026. if (!scope) // exit if the root element is not present on the page
  2027. return 0;
  2028. onevent({type: 'Repeater'});
  2029. }
  2030. };
  2031. repeater(20);
  2032. document.addEventListener(
  2033. 'DOMContentLoaded', (e) => {
  2034. domLoaded = true;
  2035. // narrow down scope to a specific element
  2036. scope = getScope(params.root);
  2037. if (!scope) // exit if the root element is not present on the page
  2038. return 0;
  2039. logger('[g] scope', scope);
  2040. // add observe mode if required
  2041. if (params.observe)
  2042. {
  2043. let params = { childList:true, subtree: true };
  2044. let observer = new MutationObserver(
  2045. function(ms)
  2046. {
  2047. for (let m of ms)
  2048. if (m.addedNodes.length)
  2049. onevent(m);
  2050. }
  2051. );
  2052. for (let node of scope)
  2053. observer.observe(node, params);
  2054. logger('[g] observer enabled');
  2055. }
  2056. onevent(e);
  2057. }, false);
  2058. // wait for a full page load to do one extra cut
  2059. win.addEventListener('load', onevent, false);
  2060. }
  2061.  
  2062. // wrap popular methods to open a new tab to catch specific behaviours
  2063. function createWindowOpenWrapper(openFunc, onClickFunc)
  2064. {
  2065. let _Document = Object.getPrototypeOf(HTMLDocument),
  2066. _createElement = _Document.prototype.createElement,
  2067. _appendChild = Element.prototype.appendChild,
  2068. fakeNative = (f) => (f.toString = () => `function ${f.name}() { [native code] }`);
  2069.  
  2070. let nt = new nullTools();
  2071. fakeNative(openFunc);
  2072.  
  2073. let parser = _createElement.call(document, 'a');
  2074. let openWhitelist = (url, parent) => {
  2075. parser.href = url;
  2076. return parser.hostname === 'www.imdb.com' || parser.hostname === 'www.kinopoisk.ru' ||
  2077. parent.hostname === 'radikal.ru' && url === void 0;
  2078. };
  2079.  
  2080. let redefineOpen = (root) => {
  2081. if ('open' in root) {
  2082. let _open = root.open.bind(root);
  2083. nt.define(root, 'open', (...args) => {
  2084. if (openWhitelist(args[0], location)) {
  2085. console.log('Whitelisted popup:', ...args);
  2086. return _open(...args);
  2087. }
  2088. return openFunc(...args);
  2089. });
  2090. }
  2091. };
  2092. redefineOpen(win);
  2093.  
  2094. function createElement(name) {
  2095. '[native code]';
  2096. // jshint validthis:true
  2097. let el = _createElement.apply(this, arguments);
  2098. // click-dispatch check for Google Chrome and similar browsers
  2099. if (el instanceof HTMLAnchorElement)
  2100. el.addEventListener('click', onClickFunc, false);
  2101. // redefine window.open in first-party frames
  2102. if (el instanceof HTMLIFrameElement || el instanceof HTMLObjectElement)
  2103. el.addEventListener('load', (e) => {
  2104. try {
  2105. redefineOpen(e.target.contentWindow);
  2106. } catch(ignore) {}
  2107. }, false);
  2108. return el;
  2109. }
  2110. fakeNative(createElement);
  2111.  
  2112. let redefineCreateElement = (obj) => {
  2113. for (let root of [obj.document, _Document.prototype]) if ('createElement' in root)
  2114. nt.define(root, 'createElement', createElement);
  2115. };
  2116. redefineCreateElement(win);
  2117.  
  2118. // wrap window.open in newly added first-party frames
  2119. Element.prototype.appendChild = function appendChild()
  2120. {
  2121. '[native code]';
  2122. let el = _appendChild.apply(this, arguments);
  2123. if (el instanceof HTMLIFrameElement) {
  2124. try {
  2125. redefineOpen(el.contentWindow);
  2126. redefineCreateElement(el.contentWindow);
  2127. } catch(ignore) {}
  2128. }
  2129. return el;
  2130. };
  2131. fakeNative(Element.prototype.appendChild);
  2132. }
  2133.  
  2134. // Function to catch and block various methods to open a new window with 3rd-party content.
  2135. // Some advertisement networks went way past simple window.open call to circumvent default popup protection.
  2136. // This funciton blocks window.open, ability to restore original window.open from an IFRAME object,
  2137. // ability to perform an untrusted (not initiated by user) click on a link, click on a link without a parent
  2138. // node or simply a link with piece of javascript code in the HREF attribute.
  2139. function preventPopups()
  2140. {
  2141. // call sandbox-me if in iframe and not whitelisted
  2142. if (inIFrame) {
  2143. win.top.postMessage({ name: 'sandbox-me', href: win.location.href }, '*');
  2144. return;
  2145. }
  2146.  
  2147. scriptLander(() => {
  2148. let open = (...args) => {
  2149. '[native code]';
  2150. console.warn('Site attempted to open a new window', args);
  2151. if (new RegExp(`^https?://${location.hostname}/`).test(args[0])) // skip extra click in case of blocked popunder
  2152. location.assign(args[0]);
  2153. return {
  2154. document: {
  2155. write: () => {},
  2156. writeln: () => {}
  2157. },
  2158. location: {}
  2159. };
  2160. };
  2161.  
  2162. let clickHandler = (e) => {
  2163. let link = e.target;
  2164. if (!link.parentNode || !e.isTrusted ||
  2165. (link.href && link.href.trim().toLowerCase().indexOf('javascript') === 0))
  2166. {
  2167. e.preventDefault();
  2168. console.warn('Blocked suspicious click event', e, 'on', e.target);
  2169. }
  2170. };
  2171.  
  2172. createWindowOpenWrapper(open, clickHandler);
  2173.  
  2174. console.log('Popup prevention enabled.');
  2175. }, nullTools, createWindowOpenWrapper);
  2176. }
  2177.  
  2178. // Helper function to close background tab if site opens itself in a new tab and then
  2179. // loads a 3rd-party page in the background one (thus performing background redirect).
  2180. function preventPopunders()
  2181. {
  2182. // create "close_me" event to call high-level window.close()
  2183. let eventName = `close_me_${Math.random().toString(36).substr(2)}`;
  2184. let callClose = () => (console.log('close call'), window.close());
  2185. window.addEventListener(eventName, callClose, true);
  2186.  
  2187. scriptLander(() => {
  2188. // get host of a provided URL with help of an anchor object
  2189. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  2190. let parseURL = document.createElement('A');
  2191. let getHost = (url) => (parseURL.href = url, parseURL.hostname);
  2192. // site went to a new tab and attempts to unload
  2193. // call for high-level close through event
  2194. let closeWindow = () => window.dispatchEvent(new CustomEvent(eventName, {}));
  2195. // check is URL local or goes to different site
  2196. let isLocal = (url) => {
  2197. if (url === location.pathname || url === location.href)
  2198. return true; // URL points to current pathname or full address
  2199. let host = getHost(url);
  2200. let site = location.hostname;
  2201. return host !== '' && // URLs with unusual protocol may have empty 'host'
  2202. (site === host || site.endsWith(`.${host}`) || host.endsWith(`.${site}`));
  2203. };
  2204.  
  2205. let _open = window.open.bind(window);
  2206. let open = (...args) => {
  2207. '[native code]';
  2208. let url = args[0];
  2209. if (url && isLocal(url))
  2210. window.addEventListener('beforeunload', closeWindow, true);
  2211. // jshint validthis:true
  2212. return _open(...args);
  2213. };
  2214.  
  2215. let clickHandler = (e) => {
  2216. if (!e.target.parentNode || !e.isTrusted)
  2217. window.addEventListener('beforeunload', closeWindow, true);
  2218. };
  2219.  
  2220. createWindowOpenWrapper(open, clickHandler);
  2221.  
  2222. console.log("Background redirect prevention enabled.");
  2223. }, `let eventName="${eventName}"`, nullTools, createWindowOpenWrapper);
  2224. }
  2225.  
  2226. // Mix between check for popups and popunders
  2227. // Significantly more agressive than both and can't be used as universal solution
  2228. function preventPopMix()
  2229. {
  2230. if (inIFrame)
  2231. {
  2232. win.top.postMessage({ name: 'sandbox-me', href: win.location.href }, '*');
  2233. return;
  2234. }
  2235.  
  2236. // create "close_me" event to call high-level window.close()
  2237. let eventName = `close_me_${Math.random().toString(36).substr(2)}`;
  2238. let callClose = () => (console.log('close call'), window.close());
  2239. window.addEventListener(eventName, callClose, true);
  2240.  
  2241. scriptLander(() => {
  2242. let _open = window.open,
  2243. parseURL = document.createElement('A');
  2244. // get host of a provided URL with help of an anchor object
  2245. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  2246. let getHost = (url) => (parseURL.href = url, parseURL.host);
  2247. // site went to a new tab and attempts to unload
  2248. // call for high-level close through event
  2249. let closeWindow = () => (_open(window.location,'_self'), window.dispatchEvent(new CustomEvent(eventName, {})));
  2250. // check is URL local or goes to different site
  2251. function isLocal(url)
  2252. {
  2253. let loc = window.location;
  2254. if (url === loc.pathname || url === loc.href)
  2255. return true; // URL points to current pathname or full address
  2256. let host = getHost(url),
  2257. site = loc.host;
  2258. if (host === '')
  2259. return false; // URLs with unusual protocol may have empty 'host'
  2260. if (host.length > site.length)
  2261. [site, host] = [host, site];
  2262. return site.includes(host, site.length - host.length);
  2263. }
  2264.  
  2265. // add check for redirect for 5 seconds, then disable it
  2266. function checkRedirect()
  2267. {
  2268. window.addEventListener('beforeunload', closeWindow, true);
  2269. setTimeout(closeWindow=>window.removeEventListener('beforeunload', closeWindow, true), 5000, closeWindow);
  2270. }
  2271.  
  2272. function open(url, name)
  2273. {
  2274. '[native code]';
  2275. if (url && isLocal(url) && (!name || name === '_blank'))
  2276. {
  2277. console.warn('Suspicious local new window', arguments);
  2278. checkRedirect();
  2279. // jshint validthis:true
  2280. return _open.apply(this, arguments);
  2281. }
  2282. console.warn('Blocked attempt to open a new window', arguments);
  2283. return {
  2284. document: {
  2285. write: () => {},
  2286. writeln: () => {}
  2287. }
  2288. };
  2289. }
  2290.  
  2291. function clickHandler(e)
  2292. {
  2293. let link = e.target,
  2294. url = link.href||'';
  2295. if (e.targetParentNode && e.isTrusted || link.target !== '_blank')
  2296. {
  2297. console.log('Link', link, 'were created dinamically, but looks fine.');
  2298. return true;
  2299. }
  2300. if (isLocal(url) && link.target === '_blank')
  2301. {
  2302. console.log('Suspicious local link', link);
  2303. checkRedirect();
  2304. return;
  2305. }
  2306. console.log('Blocked suspicious click on a link', link);
  2307. e.stopPropagation();
  2308. e.preventDefault();
  2309. }
  2310.  
  2311. createWindowOpenWrapper(open, clickHandler);
  2312.  
  2313. console.log("Mixed popups prevention enabled.");
  2314. }, `let eventName="${eventName}"`, createWindowOpenWrapper);
  2315. }
  2316. // External listener for case when site known to open popups were loaded in iframe
  2317. // It will sandbox any iframe which will send message 'forbid.popups' (preventPopups sends it)
  2318. // Some sites replace frame's window.location with data-url to run in clean context
  2319. if (!inIFrame)
  2320. {
  2321. window.addEventListener(
  2322. 'message', function(e)
  2323. {
  2324. if (!e.data || e.data.name !== 'sandbox-me' || !e.data.href)
  2325. return;
  2326. let src = e.data.href;
  2327. for (let frame of document.querySelectorAll('iframe'))
  2328. if (frame.contentWindow === e.source)
  2329. {
  2330. if (frame.hasAttribute('sandbox'))
  2331. {
  2332. if (!frame.sandbox.contains('allow-popups'))
  2333. return; // exit frame since it's already sandboxed and popups are blocked
  2334. // remove allow-popups if frame already sandboxed
  2335. frame.sandbox.remove('allow-popups');
  2336. } else {
  2337. // set sandbox mode for troublesome frame and allow scripts, forms and a few other actions
  2338. // technically allowing both scripts and same-origin allows removal of the sandbox attribute,
  2339. // but to apply content must be reloaded and this script will re-apply it in the result
  2340. frame.setAttribute('sandbox','allow-forms allow-scripts allow-presentation allow-top-navigation allow-same-origin');
  2341. }
  2342. console.log('Disallowed popups from iframe', frame);
  2343.  
  2344. // reload frame content to apply restrictions
  2345. if (!src) {
  2346. src = frame.src;
  2347. console.log('Unable to get current iframe location, reloading from src', src);
  2348. } else
  2349. console.log('Reloading iframe with URL', src);
  2350. frame.src = 'about:blank';
  2351. frame.src = src;
  2352. }
  2353. }, false
  2354. );
  2355. }
  2356.  
  2357. function selectiveEval() {
  2358. scriptLander(() => {
  2359. let nt = new nullTools();
  2360. let _eval = win.eval.bind(window);
  2361. nt.define(win, 'eval', function(...args) {
  2362. if (/_0x|location\s*?=|location.href\s*?=|location.assign\(|open\(/i.test(args[0])) {
  2363. console.log(`Skipped eval of ${args[0].slice(0, 512)}\u2026`);
  2364. return null;
  2365. }
  2366. return _eval(...args);
  2367. });
  2368. }, nullTools);
  2369. }
  2370.  
  2371. // === Scripts for specific domains ===
  2372.  
  2373. let scripts = {};
  2374. // prevent popups and redirects block
  2375. // Popups
  2376. scripts.preventPopups = {
  2377. other: [
  2378. 'biqle.ru',
  2379. 'chaturbate.com',
  2380. 'dfiles.ru',
  2381. 'hentaiz.org',
  2382. 'mirrorcreator.com',
  2383. 'online-multy.ru',
  2384. 'radikal.ru', 'rumedia.ws',
  2385. 'seedoff.cc', 'seedoff.tv',
  2386. 'thepiratebay.org', 'torseed.net',
  2387. 'unionpeer.com',
  2388. 'zippyshare.com'
  2389. ],
  2390. now: preventPopups
  2391. };
  2392. // Popunders (background redirect)
  2393. scripts.preventPopunders = {
  2394. other: [
  2395. 'lostfilm-online.ru',
  2396. 'mediafire.com', 'megapeer.org', 'megapeer.ru',
  2397. 'perfectgirls.net'
  2398. ],
  2399. now: preventPopunders
  2400. };
  2401. // PopMix (both types of popups encountered on site)
  2402. scripts['openload.co'] = {
  2403. other: ['oload.tv', 'oload.info'],
  2404. now: () => {
  2405. let nt = new nullTools();
  2406. nt.define(win, 'CNight', win.CoinHive);
  2407. if (location.pathname.startsWith('/embed/'))
  2408. {
  2409. nt.define(win, 'BetterJsPop', {
  2410. add: ((a, b) => console.warn('BetterJsPop.add', a, b)),
  2411. config: ((o) => console.warn('BetterJsPop.config', o)),
  2412. Browser: { isChrome: true }
  2413. });
  2414. nt.define(win, 'isSandboxed', nt.func(null));
  2415. nt.define(win, 'adblock', false);
  2416. nt.define(win, 'adblock2', false);
  2417. } else
  2418. preventPopMix();
  2419. }
  2420. };
  2421. scripts['turbobit.net'] = preventPopMix;
  2422.  
  2423. // workaround for moradu.com/apu.php load error handler script, not sure which ad network is this
  2424. scripts['tapochek.net'] = () => {
  2425. let _appendChild = Object.getOwnPropertyDescriptor(Node.prototype, 'appendChild');
  2426. let _appendChild_value = _appendChild.value;
  2427. _appendChild.value = function appendChild(node) {
  2428. if (this === win.document.body)
  2429. if ((node instanceof HTMLScriptElement || node instanceof HTMLStyleElement) &&
  2430. /^https?:\/\/[0-9a-f]{15}\.com\/\d+(\/|\.css)$/.test(node.src) ||
  2431. node instanceof HTMLDivElement && node.style.zIndex > 900000 &&
  2432. node.style.backgroundImage.includes('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'))
  2433. throw '...eenope!';
  2434. return _appendChild_value.apply(this, arguments);
  2435. };
  2436. Object.defineProperty(Node.prototype, 'appendChild', _appendChild);
  2437.  
  2438. preventPopups();
  2439. };
  2440.  
  2441. scripts['rustorka.com'] = {
  2442. other: ['rustorka.lib'],
  2443. now: () => scriptLander(() => {
  2444. let _eval_def = Object.getOwnPropertyDescriptor(win, 'eval');
  2445. if (!_eval_def)
  2446. return;
  2447. let _eval_val = _eval_def.value;
  2448. _eval_def.value = (...args) => {
  2449. if (args[0] && args[0].includes('antiadblock'))
  2450. return console.log('Anti-AdBlock script may run another day, but not today.');
  2451. return _eval_val.apply(this, args);
  2452. };
  2453. Object.defineProperty(win, 'eval', _eval_def);
  2454. }),
  2455. dom: () => scriptLander(() => {
  2456. let link = void 0;
  2457. document.body.addEventListener('mousedown', e => {
  2458. link = e.target.closest('a, select');
  2459. }, false);
  2460. let _open = window.open.bind(window);
  2461. let _getAttribute = Element.prototype.getAttribute;
  2462. win.open = (...args) => {
  2463. let url = args[0];
  2464. let allow = false;
  2465. if (link instanceof HTMLAnchorElement) {
  2466. // third-party post links
  2467. let href = _getAttribute.call(link, 'href');
  2468. if (link.classList.contains('postLink') &&
  2469. !link.matches(`a[href*="${location.hostname}"]`) &&
  2470. (href === url || link.href === url)) {
  2471. return _open(...args);
  2472. }
  2473. // onclick # links
  2474. if (href === '#' && /window\.open/.test(_getAttribute.call(link, 'onclick'))) {
  2475. return _open(...args);
  2476. }
  2477. // force local links to load in the current window
  2478. if (href.includes(`//${location.hostname}/`))
  2479. location.assign(href);
  2480. }
  2481. // list of image hostings under upload picture button (new comment)
  2482. if (link instanceof HTMLSelectElement &&
  2483. !url.includes(location.hostname) &&
  2484. link.value === url) {
  2485. return _open(...args);
  2486. }
  2487. // looks like tabunder
  2488. if (link === null && url === location.href)
  2489. location.replace(url); // reload current page
  2490. // other cases
  2491. console.warn(`Site attempted to open "${url}" in a new window. Source: `, link);
  2492. return {};
  2493. };
  2494. })
  2495. };
  2496.  
  2497. // other
  2498. scripts['1tv.ru'] = () => scriptLander(() => {
  2499. let nt = new nullTools();
  2500. nt.define(win, 'EUMPAntiblockConfig', nt.proxy({url: '//www.1tv.ru/favicon.ico'}));
  2501. let _EUMPConfig = void 0;
  2502. let disablePlugins = {
  2503. 'antiblock': false,
  2504. 'stat1tv': false
  2505. };
  2506. Object.defineProperty(win, 'EUMPConfig', {
  2507. enumerable: true,
  2508. get: x => _EUMPConfig,
  2509. set: x => {
  2510. let plugins = x.plugins;
  2511. if (plugins) {
  2512. let id;
  2513. for (let plugin in disablePlugins) {
  2514. id = plugins.indexOf(plugin);
  2515. if (id > -1) {
  2516. plugins.splice(id, 1);
  2517. disablePlugins[plugin] = true;
  2518. }
  2519. }
  2520. console.warn(`Player plugins: active [${plugins}], disabled [${Object.keys(disablePlugins).filter(x => disablePlugins[x])}]`);
  2521. }
  2522. _EUMPConfig = x;
  2523. }
  2524. });
  2525. }, nullTools);
  2526.  
  2527. scripts['2picsun.ru'] = {
  2528. other: [
  2529. 'pics2sun.ru', '3pics-img.ru'
  2530. ],
  2531. now: () => {
  2532. Object.defineProperty(navigator, 'userAgent', {value: 'googlebot'});
  2533. }
  2534. };
  2535.  
  2536. scripts['4pda.ru'] = {
  2537. now: () => {
  2538. // https://greasyfork.org/en/scripts/14470-4pda-unbrender
  2539. let hStyle,
  2540. isForum = document.location.href.search('/forum/') !== -1,
  2541. remove = (node) => (node ? node.parentNode.removeChild(node) : null),
  2542. afterClean = () => remove(hStyle);
  2543.  
  2544. function beforeClean()
  2545. {
  2546. // attach styles before document displayed
  2547. hStyle = createStyle([
  2548. 'html { overflow-y: scroll }',
  2549. 'article + aside * { display: none !important }',
  2550. `section[id] {${(
  2551. 'position: absolute;'+
  2552. 'width: 100%'
  2553. )}}`,
  2554. `#header + div:after {${(
  2555. 'content: "";'+
  2556. 'position: fixed;'+
  2557. 'top: 0;'+
  2558. 'left: 0;'+
  2559. 'width: 100%;'+
  2560. 'height: 100%;'+
  2561. 'background-color: #E6E7E9'
  2562. )}}`,
  2563. // http://codepen.io/Beaugust/pen/DByiE
  2564. '@keyframes spin { 100% { transform: rotate(360deg) } }',
  2565. `article + aside:after {${(
  2566. 'content: "";'+
  2567. 'position: absolute;'+
  2568. 'width: 150px;'+
  2569. 'height: 150px;'+
  2570. 'top: 150px;'+
  2571. 'left: 50%;'+
  2572. 'margin-top: -75px;'+
  2573. 'margin-left: -75px;'+
  2574. 'box-sizing: border-box;'+
  2575. 'border-radius: 100%;'+
  2576. 'border: 10px solid rgba(0, 0, 0, 0.2);'+
  2577. 'border-top-color: rgba(0, 0, 0, 0.6);'+
  2578. 'animation: spin 2s infinite linear'
  2579. )}}`
  2580. ], {id:'ubrHider'}, true);
  2581.  
  2582. // display content of a page if time to load a page is more than 2 seconds to avoid
  2583. // blocking access to a page if it is loading for too long or stuck in a loading state
  2584. setTimeout(2000, afterClean);
  2585. }
  2586.  
  2587. createStyle([
  2588. '#nav .use-ad { display: block !important }',
  2589. 'article:not(.post) + article:not(#id),'+
  2590. 'html:not(#id)>body:not(#id) a[target="_blank"] img[height="90"] { display: none !important }'
  2591. ]);
  2592.  
  2593. if (!isForum)
  2594. beforeClean();
  2595.  
  2596. // save links to non-overridden functions to use later
  2597. let protectedElems;
  2598. // protect/hide changed attributes in case site attempt to restore them
  2599. function styleProtector(eventMode)
  2600. {
  2601. let _toLowerCase = String.prototype.toLowerCase,
  2602. isStyleText = (t) => (_toLowerCase.call(t) === 'style'),
  2603. protectedElems = new WeakMap();
  2604. function protoOverride(element, functionName, isStyleCheck, returnIfProtected)
  2605. {
  2606. let originalFunction = element.prototype[functionName];
  2607. element.prototype[functionName] = function wrapper()
  2608. {
  2609. if (protectedElems.has(this) && isStyleCheck(arguments[0]))
  2610. return returnIfProtected(this, arguments);
  2611. return originalFunction.apply(this, arguments);
  2612. };
  2613. }
  2614. protoOverride(Element, 'removeAttribute', isStyleText, () => undefined);
  2615. protoOverride(Element, 'hasAttribute', isStyleText, (_this) => protectedElems.get(_this) !== null);
  2616. protoOverride(Element, 'setAttribute', isStyleText, (_this, args) => protectedElems.set(_this, args[1]));
  2617. protoOverride(Element, 'getAttribute', isStyleText, (_this) => protectedElems.get(_this));
  2618. if (!eventMode)
  2619. return protectedElems;
  2620. else
  2621. {
  2622. let e = document.createEvent('Event');
  2623. e.initEvent('protoOverride', false, false);
  2624. window.protectedElems = protectedElems;
  2625. window.dispatchEvent(e);
  2626. }
  2627. }
  2628. if (!isFirefox)
  2629. protectedElems = styleProtector(false);
  2630. else
  2631. {
  2632. let script = document.createElement('script');
  2633. script.textContent = `(${styleProtector.toString()})(true);`;
  2634. window.addEventListener(
  2635. 'protoOverride', function protoOverrideCallback(e)
  2636. {
  2637. if (win.protectedElems) {
  2638. protectedElems = win.protectedElems;
  2639. delete win.protectedElems;
  2640. }
  2641. document.removeEventListener('protoOverride', protoOverrideCallback, true);
  2642. }, true
  2643. );
  2644. _appendChild(script);
  2645. _removeChild(script);
  2646. }
  2647.  
  2648. // clean a page
  2649. window.addEventListener(
  2650. 'DOMContentLoaded', function()
  2651. {
  2652. let width = () => window.innerWidth || _de.clientWidth || document.body.clientWidth || 0;
  2653. let height = () => window.innerHeight || _de.clientHeight || document.body.clientHeight || 0;
  2654.  
  2655. if (isForum)
  2656. {
  2657. let si = document.querySelector('#logostrip');
  2658. if (si)
  2659. remove(si.parentNode.nextSibling);
  2660. }
  2661.  
  2662. // clear background in the download frame
  2663. if (location.pathname.startsWith('/forum/dl/')) {
  2664. let setBackground = node => _setAttribute.call(
  2665. node,
  2666. 'style', (_getAttribute.call(node, 'style') || '') +
  2667. ';background-color:#4ebaf6!important'
  2668. );
  2669. setBackground(document.body);
  2670. for (let itm of document.querySelectorAll('body > div'))
  2671. if (!itm.querySelector('.dw-fdwlink, .content') && !itm.classList.contains('footer')) {
  2672. remove(itm);
  2673. } else {
  2674. setBackground(itm);
  2675. }
  2676. }
  2677.  
  2678. if (isForum) // Do not continue if it's a forum
  2679. return;
  2680.  
  2681. {
  2682. let si = document.querySelector('#header');
  2683. if (si)
  2684. {
  2685. let rem = si.previousSibling;
  2686. while (rem)
  2687. {
  2688. si = rem.previousSibling;
  2689. remove(rem);
  2690. rem = si;
  2691. }
  2692. }
  2693. }
  2694.  
  2695. for (let itm of document.querySelectorAll('#nav li[class]'))
  2696. if (itm && itm.querySelector('a[href^="/tag/"]'))
  2697. remove(itm);
  2698.  
  2699. let style, result,
  2700. fakeStyles = new WeakMap(),
  2701. styleProxy = {
  2702. get: function(target, prop)
  2703. {
  2704. let fakeStyle = fakeStyles.get(target);
  2705. return ((prop in fakeStyle) ? fakeStyle : target)[prop];
  2706. },
  2707. set: function(target, prop, value)
  2708. {
  2709. let fakeStyle = fakeStyles.get(target);
  2710. ((prop in fakeStyle) ? fakeStyle : target)[prop] = value;
  2711. return true;
  2712. }
  2713. };
  2714. for (let itm of document.querySelectorAll('DIV, A'))
  2715. {
  2716. if (itm.tagName ==='DIV' &&
  2717. itm.offsetWidth > 0.95 * width() &&
  2718. itm.offsetHeight > 0.85 * height())
  2719. {
  2720. style = window.getComputedStyle(itm, null);
  2721. result = [];
  2722.  
  2723. if (style.backgroundImage !== 'none')
  2724. result.push('background-image:none!important');
  2725.  
  2726. if (style.backgroundColor !== 'transparent' &&
  2727. style.backgroundColor !== 'rgba(0, 0, 0, 0)')
  2728. result.push('background-color:transparent!important');
  2729.  
  2730. if (result.length)
  2731. {
  2732. if (itm.getAttribute('style'))
  2733. result.unshift(itm.getAttribute('style'));
  2734.  
  2735. fakeStyles.set(itm.style, {
  2736. 'backgroundImage': itm.style.backgroundImage,
  2737. 'backgroundColor': itm.style.backgroundColor
  2738. });
  2739.  
  2740. try {
  2741. Object.defineProperty(itm, 'style', {
  2742. value: new Proxy(itm.style, styleProxy),
  2743. enumerable: true
  2744. });
  2745. } catch (e) {
  2746. console.log('Unable to protect style property.', e);
  2747. }
  2748.  
  2749. if (protectedElems)
  2750. protectedElems.set(itm, _getAttribute.call(itm, 'style'));
  2751.  
  2752. _setAttribute.call(itm, 'style', result.join(';'));
  2753. }
  2754. }
  2755. if (itm.tagName ==='A' &&
  2756. (itm.offsetWidth > 0.95 * width() ||
  2757. itm.offsetHeight > 0.85 * height()))
  2758. {
  2759. if (protectedElems)
  2760. protectedElems.set(itm, _getAttribute.call(itm, 'style'));
  2761.  
  2762. _setAttribute.call(itm, 'style', 'display:none!important');
  2763. }
  2764. }
  2765.  
  2766. for (let itm of document.querySelectorAll('ASIDE>DIV'))
  2767. if ( ((itm.querySelector('script, iframe, a[href*="/ad/www/"]') ||
  2768. itm.querySelector('img[src$=".gif"]:not([height="0"]), img[height="400"]')) &&
  2769. !itm.classList.contains('post') ) || !itm.childNodes.length )
  2770. remove(itm);
  2771.  
  2772. document.body.setAttribute('style', (document.body.getAttribute('style')||'')+';background-color:#E6E7E9!important');
  2773.  
  2774. // display content of the page
  2775. afterClean();
  2776. }
  2777. );
  2778. }
  2779. };
  2780.  
  2781. scripts['adhands.ru'] = () => scriptLander(() => {
  2782. let nt = new nullTools();
  2783. try {
  2784. let _adv;
  2785. Object.defineProperty(win, 'adv', {
  2786. get: () => _adv,
  2787. set: (v) => {
  2788. console.log('Blocked advert on adhands.ru.');
  2789. nt.define(v, 'advert', '');
  2790. _adv = v;
  2791. }
  2792. });
  2793. } catch (ignore) {
  2794. if (!win.adv)
  2795. console.log('Unable to locate advert on adhands.ru.');
  2796. else {
  2797. console.log('Blocked advert on adhands.ru.');
  2798. nt.define(win.adv, 'advert', '');
  2799. }
  2800. }
  2801. }, nullTools);
  2802.  
  2803. scripts['all-episodes.tv'] = () => {
  2804. let nt = new nullTools();
  2805. nt.define(win, 'perX1', 2);
  2806. createStyle('#advtss, #ad3, a[href*="/ad.admitad.com/"] { display:none!important }');
  2807. };
  2808.  
  2809. scripts['allhentai.ru'] = () => {
  2810. selectiveEval();
  2811. preventPopups();
  2812. scriptLander(() => {
  2813. let _onerror = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onerror');
  2814. if (!_onerror)
  2815. return;
  2816. _onerror.set = (...args) => console.log(args[0].toString());
  2817. Object.defineProperty(HTMLElement.prototype, 'onerror', _onerror);
  2818. });
  2819. };
  2820.  
  2821. scripts['allmovie.pro'] = {
  2822. other: ['rufilmtv.org'],
  2823. dom: function()
  2824. {
  2825. // pretend to be Android to make site use different played for ads
  2826. if (isSafari)
  2827. return;
  2828. Object.defineProperty(navigator, 'userAgent', {
  2829. 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'; },
  2830. enumerable: true
  2831. });
  2832. }
  2833. };
  2834.  
  2835. scripts['anidub-online.ru'] = {
  2836. other: ['online.anidub.com'],
  2837. dom: function()
  2838. {
  2839. if (win.ogonekstart1)
  2840. win.ogonekstart1 = () => console.log("Fire in the hole!");
  2841. },
  2842. now: () => createStyle([
  2843. '.background {background: none!important;}',
  2844. '.background > script + div,'+
  2845. '.background > script ~ div:not([id]):not([class]) + div[id][class]'+
  2846. '{display:none!important}'
  2847. ])
  2848. };
  2849.  
  2850. scripts['drive2.ru'] = () => gardener('.c-block:not([data-metrika="recomm"]),.o-grid__item', />Реклама<\//i);
  2851.  
  2852. scripts['fishki.net'] = () => {
  2853. scriptLander(() => {
  2854. let nt = new nullTools();
  2855. let fishki = {};
  2856. nt.define(fishki, 'adv', nt.proxy({
  2857. afterAdblockCheck: nt.func(null),
  2858. refreshFloat: nt.func(null)
  2859. }));
  2860. nt.define(fishki, 'is_adblock', false);
  2861. nt.define(win, 'fishki', fishki);
  2862. }, nullTools);
  2863. gardener('.drag_list > .drag_element, .list-view > .paddingtop15, .post-wrap', /543769|Новости\sпартнеров|Полезная\sреклама/);
  2864. };
  2865.  
  2866. scripts['gidonline.club'] = () => createStyle('.tray > div[style] {display: none!important}');
  2867.  
  2868. scripts['hdgo.cc'] = {
  2869. other: ['46.30.43.38', 'couber.be'],
  2870. now: () => (new MutationObserver(
  2871. (ms) => {
  2872. let m, node;
  2873. for (m of ms) for (node of m.addedNodes)
  2874. if (node.tagName instanceof HTMLScriptElement && _getAttribute.call(node, 'onerror') !== null)
  2875. node.removeAttribute('onerror');
  2876. }
  2877. )).observe(document.documentElement, { childList:true, subtree: true })
  2878. };
  2879.  
  2880. scripts['gismeteo.ru'] = {
  2881. other: ['gismeteo.ua'],
  2882. now: () => gardener('div > script', /AdvManager/i, { observe: true, parent: 'div' })
  2883. };
  2884.  
  2885. scripts['hdrezka.ag'] = () => {
  2886. Object.defineProperty(win, 'ab', { value: false, enumerable: true });
  2887. gardener('div[id][onclick][onmouseup][onmousedown]', /onmouseout/i);
  2888. };
  2889.  
  2890. scripts['hideip.me'] = {
  2891. now: () => scriptLander(() => {
  2892. let _innerHTML = Object.getOwnPropertyDescriptor(Element.prototype, 'innerHTML');
  2893. let _set_innerHTML = _innerHTML.set;
  2894. let _innerText = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'innerText');
  2895. let _get_innerText = _innerText.get;
  2896. let div = document.createElement('div');
  2897. _innerHTML.set = function(...args) {
  2898. _set_innerHTML.call(div, args[0].replace('i','a'));
  2899. if (args[0] && /[рp][еe]кл/.test(_get_innerText.call(div))||
  2900. /(\d\d\d?\.){3}\d\d\d?\:\d/.test(_get_innerText.call(this)) ) {
  2901. console.log('Anti-Adblock killed.');
  2902. return true;
  2903. }
  2904. _set_innerHTML.apply(this, args);
  2905. };
  2906. Object.defineProperty(Element.prototype, 'innerHTML', _innerHTML);
  2907. Object.defineProperty(win, 'adblock', {
  2908. get: x => false,
  2909. set: x => null,
  2910. enumerable: true
  2911. });
  2912. let _$ = {};
  2913. let _$_map = new WeakMap();
  2914. let _gOPD = Object.getOwnPropertyDescriptor(Object, 'getOwnPropertyDescriptor');
  2915. let _val_gOPD = _gOPD.value;
  2916. _gOPD.value = function(...args) {
  2917. let _res = _val_gOPD.apply(this, args);
  2918. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery')) {
  2919. delete _res.get;
  2920. delete _res.set;
  2921. _res.value = win[args[1]];
  2922. }
  2923. return _res;
  2924. };
  2925. Object.defineProperty(Object, 'getOwnPropertyDescriptor', _gOPD);
  2926. let getJQWrap = (n) => {
  2927. let name = n;
  2928. return {
  2929. enumerable: true,
  2930. get: x => _$[name],
  2931. set: x => {
  2932. if (_$_map.has(x)) {
  2933. _$[name] = _$_map.get(x);
  2934. return true;
  2935. }
  2936. if (x === _$.$ || x === _$.jQuery) {
  2937. _$[name] = x;
  2938. return true;
  2939. }
  2940. _$[name] = new Proxy(x, {
  2941. apply: (t, o, args) => {
  2942. let _res = t.apply(o, args);
  2943. if (_$_map.has(_res.is)) {
  2944. _res.is = _$_map.get(_res.is);
  2945. } else {
  2946. let _is = _res.is;
  2947. _res.is = function(...args) {
  2948. if (args[0] === ':hidden')
  2949. return false;
  2950. return _is.apply(this, args);
  2951. };
  2952. _$_map.set(_is, _res.is);
  2953. }
  2954. return _res;
  2955. }
  2956. });
  2957. _$_map.set(x, _$[name]);
  2958. return true;
  2959. }
  2960. };
  2961. };
  2962. Object.defineProperty(win, '$', getJQWrap('$'));
  2963. Object.defineProperty(win, 'jQuery', getJQWrap('jQuery'));
  2964. let _dP = Object.defineProperty;
  2965. Object.defineProperty = function(...args) {
  2966. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery'))
  2967. return void 0;
  2968. return _dP.apply(this, args);
  2969. };
  2970. })
  2971. };
  2972.  
  2973. scripts['igra-prestoloff.cx'] = () => scriptLander(() => {
  2974. let nt = new nullTools();
  2975. /*jslint evil: true */ // yes, evil, I know
  2976. let _write = document.write.bind(document);
  2977. /*jslint evil: false */
  2978. nt.define(document, 'write', t => {
  2979. let id = t.match(/jwplayer\("(\w+)"\)/i);
  2980. if (id && id[1]) {
  2981. return _write(`<div id="${id[1]}"></div>${t}`);
  2982. } else {
  2983. return _write('');
  2984. }
  2985. });
  2986. });
  2987.  
  2988. scripts['imageban.ru'] = {
  2989. now: () => {
  2990. Object.defineProperty(win, 'V7x1J', { get: () => null });
  2991. //preventPopunders();
  2992. }
  2993. };
  2994.  
  2995. scripts['kinopoisk.ru'] = {
  2996. now: () => {
  2997. // set no-branding body style
  2998. createStyle('body:not(#id) { background: #d5d5d5 url(/images/noBrandBg.jpg) 50% 0 no-repeat !important }');
  2999. },
  3000. dom: () => {
  3001. (style => style ? style.parentNode.removeChild(style) : console.log('Unable to locate branding style.')
  3002. )(_de.querySelector('#branding-style'));
  3003. }
  3004. };
  3005.  
  3006. scripts['korrespondent.net'] = {
  3007. now: () => scriptLander(() => {
  3008. let nt = new nullTools();
  3009. nt.define(win, 'holder', function(id) {
  3010. let div = document.getElementById(id);
  3011. if (!div)
  3012. return;
  3013. if (div.parentNode.classList.contains('col__sidebar')) {
  3014. div.parentNode.appendChild(div);
  3015. div.style.height = '300px';
  3016. }
  3017. });
  3018. }, nullTools),
  3019. dom: () => {
  3020. for (let frame of document.querySelectorAll('.unit-side-informer > iframe'))
  3021. frame.parentNode.style.width = '1px';
  3022. }
  3023. };
  3024.  
  3025. scripts['mail.ru'] = () => scriptLander(() => {
  3026. let nt = new nullTools();
  3027. // Trick to prevent mail.ru from removing 3rd-party styles
  3028. nt.define(Object.prototype, 'restoreVisibility', nt.func(null), false);
  3029. // Disable some of their counters
  3030. nt.define(win, 'rb_counter', nt.func(null, 'rb_counter'));
  3031. if (location.hostname !== 'e.mail.ru')
  3032. nt.define(win, 'createRadar', nt.func(nt.func(null, 'aRadar'), 'createRadar'));
  3033. else
  3034. nt.define(win, 'aRadar', nt.func(null, 'aRadar'));
  3035.  
  3036. // Disable page scrambler on mail.ru to let extensions easily block ads there
  3037. function defineLocator(root)
  3038. {
  3039. let _locator;
  3040. let fishnet = {
  3041. apply: (target, thisArg, args) => {
  3042. console.log(`locator.${target._name}(${JSON.stringify(args).slice(1,-1)})`);
  3043. return target.apply(thisArg, args);
  3044. }
  3045. };
  3046.  
  3047. function wrapLocator(locator)
  3048. {
  3049. if ('setup' in locator)
  3050. {
  3051. let _setup = locator.setup;
  3052. locator.setup = function(o)
  3053. {
  3054. if ('enable' in o)
  3055. {
  3056. o.enable = false;
  3057. console.log('Disable mimic mode.');
  3058. }
  3059. if ('links' in o)
  3060. {
  3061. o.links = [];
  3062. console.log('Call with empty list of sheets.');
  3063. }
  3064. return _setup.call(this, o);
  3065. };
  3066. locator.insertSheet = () => console.log('Ignore insertSheet.');
  3067. locator.wrap = () => console.log('Ignore wrap.');
  3068. }
  3069. try {
  3070. let names = [];
  3071. for (let name in locator)
  3072. if (locator[name] instanceof Function) {
  3073. locator[name]._name = name;
  3074. locator[name] = new Proxy(locator[name], fishnet);
  3075. names.push(name);
  3076. }
  3077. console.log(`[locator] wrapped properties: ${names.join(', ')}`);
  3078. } catch(e) {
  3079. console.log(e);
  3080. }
  3081. _locator = locator;
  3082. }
  3083.  
  3084. if ('locator' in root && root.locator)
  3085. {
  3086. console.log('Found existing "locator" object. :|');
  3087. _locator = root.locator;
  3088. wrapLocator(root.locator);
  3089. }
  3090.  
  3091. let loc_desc = Object.getOwnPropertyDescriptor(root, 'locator');
  3092. if (!loc_desc || loc_desc.set !== wrapLocator)
  3093. try {
  3094. Object.defineProperty(root, 'locator', {
  3095. set: wrapLocator,
  3096. get: () => _locator
  3097. });
  3098. } catch (err) {
  3099. console.log('Unable to redefine "locator" object!!!', err);
  3100. }
  3101. }
  3102.  
  3103. function defineDetector(mr)
  3104. {
  3105. let __ = mr._ || {};
  3106.  
  3107. if ('HONEYPOT' in __)
  3108. {
  3109. console.log('Disarming existing detector instance. :|', JSON.stringify(__));
  3110. nt.define(__, 'HONEYPOT', '.honeypot_fake_class_to_miss');
  3111. nt.define(__, 'STUCK_IN_POT', false);
  3112. }
  3113.  
  3114. __ = new Proxy(__, {
  3115. get: (t, p) => t[p],
  3116. set: (t, p, v) => {
  3117. console.log(`mr._.${p} =`, v);
  3118. if (['HONEYPOT', 'STUCK_IN_POT'].includes(p))
  3119. console.log('Not changed.');
  3120. t[p] = v; // setter in nt.define will prevent this when needed
  3121. return true;
  3122. }
  3123. });
  3124. Object.defineProperty(mr, '_', {
  3125. enumerable: true,
  3126. value: __
  3127. });
  3128. }
  3129.  
  3130. if (location.hostname === 'e.mail.ru')
  3131. defineLocator(win);
  3132. else {
  3133. try {
  3134. let _mr;
  3135. Object.defineProperty(win, 'mr', {
  3136. enumerable: true,
  3137. get: () => _mr,
  3138. set: (v) => {
  3139. if (v === _mr)
  3140. return true;
  3141. console.log('Trapped new "mr" object.');
  3142. defineLocator(v.mimic ? v.mimic : v);
  3143. defineDetector(v);
  3144. _mr = v;
  3145. }
  3146. });
  3147. if (!('mr' in win))
  3148. throw 'Wat!?';
  3149. } catch (e) {
  3150. console.log('Found existing "mr" object.', e instanceof TypeError ? '' : e);
  3151. defineLocator(win.mr);
  3152. defineDetector(win.mr);
  3153. }
  3154. }
  3155. }, nullTools);
  3156.  
  3157. scripts['megogo.net'] = {
  3158. now: () => {
  3159. let nt = new nullTools();
  3160. nt.define(win, 'adBlock', false);
  3161. nt.define(win, 'showAdBlockMessage', nt.func(null));
  3162. }
  3163. };
  3164.  
  3165. scripts['naruto-base.su'] = () => gardener('div[id^="entryID"],.block', /href="http.*?target="_blank"/i);
  3166.  
  3167. scripts['overclockers.ru'] = {
  3168. now: () => scriptLander(() => {
  3169. let _innerHTML = Object.getOwnPropertyDescriptor(Element.prototype, 'innerHTML');
  3170. let _set_innerHTML = _innerHTML.set;
  3171. _innerHTML.set = function() {
  3172. if (this === document.body) {
  3173. console.log('Anti-Adblock killed.');
  3174. return true;
  3175. }
  3176. _set_innerHTML.apply(this, arguments);
  3177. };
  3178. Object.defineProperty(Element.prototype, 'innerHTML', _innerHTML);
  3179. })
  3180. };
  3181. scripts['forums.overclockers.ru'] = {
  3182. now: () => {
  3183. createStyle('.needblock {position: fixed; left: -10000px}');
  3184. Object.defineProperty(win, 'adblck', {
  3185. get: () => 'no',
  3186. set: () => undefined,
  3187. enumerable: true
  3188. });
  3189. }
  3190. };
  3191.  
  3192. scripts['pb.wtf'] = {
  3193. other: ['piratbit.org', 'piratbit.ru'],
  3194. now: () => {
  3195. // line above topic content and images in the slider in the header
  3196. gardener(
  3197. 'a[href^="/exit/"], a[href^="/fxt/"], a[href$="=="]',
  3198. /img|Реклама|center/i,
  3199. { root: '.release-navbar,#page_content', observe: true, parent: 'div,tr' }
  3200. );
  3201. // ads in comments
  3202. gardener('img[data-name="PiraBo"]', /./i, {root:'#main_content .table', observe:true, parent:'tr'});
  3203. }
  3204. };
  3205.  
  3206. scripts['pikabu.ru'] = () => gardener('.story', /story__author[^>]+>ads</i, {root: '.inner_wrap', observe: true});
  3207.  
  3208. scripts['peka2.tv'] = () => {
  3209. let bodyClass = 'body--branding';
  3210. let checkNode = node => {
  3211. for (let className of node.classList)
  3212. if (className.includes('banner') || className === bodyClass) {
  3213. _removeAttribute.call(node, 'style');
  3214. node.classList.remove(className);
  3215. for (let attr of Array.from(node.attributes)) {
  3216. if (attr.name.startsWith('advert'))
  3217. _removeAttribute.call(node, attr.name);
  3218. }
  3219. }
  3220. };
  3221. (new MutationObserver(ms => {
  3222. let m, node;
  3223. for (m of ms) for (node of m.addedNodes)
  3224. if (node instanceof HTMLElement)
  3225. checkNode(node);
  3226. })).observe(_de, {childList: true, subtree: true});
  3227. (new MutationObserver(ms => {
  3228. for (let m of ms)
  3229. checkNode(m.target);
  3230. })).observe(_de, {attributes: true, subtree: true, attributeFilter: ['class']});
  3231. };
  3232.  
  3233. scripts['qrz.ru'] = {
  3234. now: () => {
  3235. let nt = new nullTools();
  3236. nt.define(win, 'ab', false);
  3237. nt.define(win, 'tryMessage', nt.func(null));
  3238. }
  3239. };
  3240.  
  3241. scripts['razlozhi.ru'] = {
  3242. now: () => {
  3243. for (let func of ['createShadowRoot', 'attachShadow'])
  3244. if (func in Element.prototype)
  3245. Element.prototype[func] = function(){ return this.cloneNode(); };
  3246. }
  3247. };
  3248.  
  3249. scripts['rbc.ru'] = {
  3250. dom: () => {
  3251. let _preventDefault = Event.prototype.preventDefault;
  3252. Event.prototype.preventDefault = function preventDefault()
  3253. {
  3254. let t = this.target;
  3255. if (t instanceof HTMLAnchorElement || t.closest('A'))
  3256. throw new Error('an.yandex redirect prevention');
  3257. return _preventDefault.call(this);
  3258. };
  3259.  
  3260. function cleaner(nodes)
  3261. {
  3262. for (let node of nodes)
  3263. {
  3264. if (!node.classList || !node.classList.contains('js-yandex-counter'))
  3265. continue;
  3266. node.classList.remove('js-yandex-counter');
  3267. node.removeAttribute('data-yandex-name');
  3268. node.removeAttribute('data-yandex-params');
  3269. }
  3270. }
  3271. cleaner(_de.querySelectorAll('.js-yandex-counter'));
  3272.  
  3273. (new MutationObserver(
  3274. ms => { for (let m of ms) cleaner(m.addedNodes); }
  3275. )).observe(_de, {childList: true, subtree: true});
  3276. }
  3277. };
  3278.  
  3279. scripts['rp5.ru'] = {
  3280. other: ['rp5.by', 'rp5.kz', 'rp5.ua'],
  3281. now: () => gardener('div[id][class]', /\?AdvertMgmt=|adsbygoogle/, { root: '#content-wrapper', log: true })
  3282. };
  3283.  
  3284. scripts['rutube.ru'] = () => scriptLander(() => {
  3285. let _parse = JSON.parse.bind(JSON);
  3286. let _skip_enabled = false;
  3287. JSON.parse = (...args) => {
  3288. let res = _parse(...args),
  3289. log = false;
  3290. if (!res)
  3291. return res;
  3292. // parse player configuration
  3293. if ('appearance' in res || 'video_balancer' in res) {
  3294. log = true;
  3295. if ('appearance' in res) {
  3296. res.appearance.forbid_seek = false;
  3297. res.appearance.forbid_timeline_preview = false;
  3298. }
  3299. _skip_enabled = !!res.remove_unseekable_blocks;
  3300. res.advert = [];
  3301. for (let limit of res.limits)
  3302. limit.limit = 0;
  3303. res.yast = null;
  3304. res.yast_live_online = null;
  3305. Object.defineProperty(res, 'stat', {
  3306. get: x => [],
  3307. set: x => true,
  3308. enumerable: true
  3309. });
  3310. }
  3311.  
  3312. // parse video configuration
  3313. if ('video_url' in res) {
  3314. log = true;
  3315. if ('cuepoints' in res && !_skip_enabled)
  3316. for (let point of res.cuepoints) {
  3317. point.is_pause = false;
  3318. point.show_navigation = true;
  3319. point.forbid_seek = false;
  3320. }
  3321. }
  3322.  
  3323. if (log)
  3324. console.log('[rutube]', res);
  3325. return res;
  3326. };
  3327. });
  3328.  
  3329. scripts['simpsonsua.com.ua'] = () => scriptLander(() => {
  3330. let _addEventListener = Object.getPrototypeOf(HTMLDocument).prototype.addEventListener;
  3331. document.addEventListener = function(event, callback) {
  3332. if (event === 'DOMContentLoaded' && callback.toString().includes('show_warning'))
  3333. return;
  3334. return _addEventListener.apply(this, arguments);
  3335. };
  3336. });
  3337.  
  3338. scripts['spaces.ru'] = () => {
  3339. gardener('div:not(.f-c_fll) > a[href*="spaces.ru/?Cl="]', /./, { parent: 'div' });
  3340. gardener('.js-banner_rotator', /./, { parent: '.widgets-group' });
  3341. };
  3342.  
  3343. scripts['spam-club.blogspot.co.uk'] = () => {
  3344. let _clientHeight = Object.getOwnPropertyDescriptor(Element.prototype, 'clientHeight'),
  3345. _clientWidth = Object.getOwnPropertyDescriptor(Element.prototype, 'clientWidth');
  3346. let wrapGetter = (getter) => {
  3347. let _getter = getter;
  3348. return function()
  3349. {
  3350. let _size = _getter.apply(this, arguments);
  3351. return _size ? _size : 1;
  3352. };
  3353. };
  3354. _clientHeight.get = wrapGetter(_clientHeight.get);
  3355. _clientWidth.get = wrapGetter(_clientWidth.get);
  3356. Object.defineProperty(Element.prototype, 'clientHeight', _clientHeight);
  3357. Object.defineProperty(Element.prototype, 'clientWidth', _clientWidth);
  3358. let _onload = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onload'),
  3359. _set_onload = _onload.set;
  3360. _onload.set = function()
  3361. {
  3362. if (this instanceof HTMLImageElement)
  3363. return true;
  3364. _set_onload.apply(this, arguments);
  3365. };
  3366. Object.defineProperty(HTMLElement.prototype, 'onload', _onload);
  3367. };
  3368.  
  3369. scripts['sport-express.ru'] = () => gardener('.js-relap__item',/>Реклама\s+<\//, {root:'.container', observe: true});
  3370.  
  3371. scripts['sports.ru'] = {
  3372. now: () => {
  3373. gardener('.aside-news-list__item', /aside-news-list__advert/i, {root:'.columns-layout__left', observe: true});
  3374. gardener('.material-list__item', /Реклама/i, {root:'.columns-layout', observe: true});
  3375. // extra functionality: shows/hides panel at the top depending on scroll direction
  3376. createStyle([
  3377. '.user-panel__fixed { transition: top 0.2s ease-in-out!important; }',
  3378. '.user-panel-up { top: -40px!important }'
  3379. ], {id: 'userPanelSlide'}, false);
  3380. },
  3381. dom: () => {
  3382. (function lookForPanel()
  3383. {
  3384. let panel = document.querySelector('.user-panel__fixed');
  3385. if (!panel)
  3386. setTimeout(lookForPanel, 100);
  3387. else
  3388. window.addEventListener(
  3389. 'wheel', function(e)
  3390. {
  3391. if (e.deltaY > 0 && !panel.classList.contains('user-panel-up'))
  3392. panel.classList.add('user-panel-up');
  3393. else if (e.deltaY < 0 && panel.classList.contains('user-panel-up'))
  3394. panel.classList.remove('user-panel-up');
  3395. }, false
  3396. );
  3397. })();
  3398. }
  3399. };
  3400.  
  3401. scripts['stealthz.ru'] = {
  3402. dom: () => {
  3403. // skip timeout
  3404. let $ = document.querySelector.bind(document);
  3405. let [timer_1, timer_2] = [$('#timer_1'), $('#timer_2')];
  3406. if (!timer_1 || !timer_2)
  3407. return;
  3408. timer_1.style.display = 'none';
  3409. timer_2.style.display = 'block';
  3410. }
  3411. };
  3412.  
  3413. scripts['yap.ru'] = {
  3414. other: ['yaplakal.com'],
  3415. now: () => {
  3416. gardener('form > table[id^="p_row_"]:nth-of-type(2)', /member1438|Administration/);
  3417. gardener('.icon-comments', /member1438|Administration|\/go\/\?http/, {parent:'tr', siblings:-2});
  3418. }
  3419. };
  3420.  
  3421. scripts['rambler.ru'] = {
  3422. other: ['championat.com','gazeta.ru','media.eagleplatform.com','lenta.ru', 'quto.ru'],
  3423. now: () => scriptLander(() => {
  3424. // Prevent autoplay
  3425. if (!('EaglePlayer' in win)) {
  3426. let _EaglePlayer = void 0;
  3427. Object.defineProperty(win, 'EaglePlayer', {
  3428. enumerable: true,
  3429. get: x => _EaglePlayer,
  3430. set: x => {
  3431. if (x === _EaglePlayer)
  3432. return true;
  3433. _EaglePlayer = x;
  3434. let _init = void 0;
  3435. Object.defineProperty(_EaglePlayer.prototype, 'init', {
  3436. enumerable: true,
  3437. set: x => _init = x,
  3438. get: function() {
  3439. let _self = this;
  3440. if (_self.options) {
  3441. Object.defineProperty(this.options, 'autoplay', {
  3442. enumerable: true,
  3443. get: x => false,
  3444. set: x => null
  3445. });
  3446. }
  3447. if (_self.options && _self.options.el && inIFrame) {
  3448. let addListener = (player) => {
  3449. console.log('Attached autostop');
  3450. player.addEventListener('canplay', e => {
  3451. e.target.play = () => console.log('Applied autostop.');
  3452. setTimeout(player => {
  3453. delete player.play;
  3454. console.log('Detached autostop');
  3455. }, 1500, e.target);
  3456. }, false);
  3457. };
  3458. (new MutationObserver(ms => {
  3459. let m, node;
  3460. for (m of ms) for (node of m.addedNodes)
  3461. if (node instanceof HTMLVideoElement)
  3462. addListener(node);
  3463. })).observe(this.options.el, { childList: true, subtree: true });
  3464. }
  3465. return _init;
  3466. }
  3467. });
  3468. }
  3469. });
  3470. let _setAttribute = Element.prototype.setAttribute;
  3471. let isAutoplay = /^autoplay$/i;
  3472. Element.prototype.setAttribute = function setAttribute(name)
  3473. {
  3474. if (!this._stopped && isAutoplay.test(name))
  3475. {
  3476. console.log('Prevented assigning autoplay attribute.');
  3477. return null;
  3478. }
  3479. return _setAttribute.apply(this, arguments);
  3480. };
  3481. } else if (inIFrame) {
  3482. let _setAttribute = Element.prototype.setAttribute;
  3483. let isAutoplay = /^autoplay$/i;
  3484. Element.prototype.setAttribute = function setAttribute(name)
  3485. {
  3486. if (!this._stopped && isAutoplay.test(name))
  3487. {
  3488. console.log('Prevented assigning autoplay attribute.');
  3489. this._stopped = true;
  3490. this.play = () => {
  3491. console.log('Prevented attempt to force-start playback.');
  3492. delete this.play;
  3493. };
  3494. return null;
  3495. }
  3496. return _setAttribute.apply(this, arguments);
  3497. };
  3498. }
  3499. if (location.hostname.endsWith('.media.eagleplatform.com'))
  3500. return;
  3501. let CSSRuleProto = 'cssText' in CSSRule.prototype ? CSSRule.prototype : CSSStyleRule.prototype;
  3502. let _cssText = Object.getOwnPropertyDescriptor(CSSRuleProto, 'cssText');
  3503. let _cssText_get = _cssText.get;
  3504. _cssText.configurable = false;
  3505. _cssText.get = function()
  3506. {
  3507. let cssText = _cssText_get.call(this);
  3508. if (cssText.includes('content:'))
  3509. {
  3510. console.log('Blocked access to suspicious cssText:', cssText.slice(0,60), '\u2026', cssText.length);
  3511. return null;
  3512. }
  3513. return cssText;
  3514. };
  3515. Object.defineProperty(CSSRuleProto, 'cssText', _cssText);
  3516. // fake global Adf object
  3517. let nt = new nullTools();
  3518. let Adf_banner = {};
  3519. [
  3520. 'reloadssp', 'sspScroll',
  3521. 'sspRich', 'ssp'
  3522. ].map(name => Adf_banner[name] = nt.proxy(() => new Promise((r,j) => r({status: true}))));
  3523. nt.define(win, 'Adf', nt.proxy({
  3524. banner: nt.proxy(Adf_banner)
  3525. }));
  3526. // extra script to remove partner news on gazeta.ru
  3527. if (!location.hostname.includes('gazeta.ru'))
  3528. return;
  3529. (new MutationObserver(
  3530. (ms) => {
  3531. let m, node, header;
  3532. for (m of ms) for (node of m.addedNodes)
  3533. if (node instanceof HTMLDivElement && node.matches('.sausage'))
  3534. {
  3535. header = node.querySelector('.sausage-header');
  3536. if (header && /новости\s+партн[её]ров/i.test(header.textContent))
  3537. node.style.display = 'none';
  3538. }
  3539. }
  3540. )).observe(document.documentElement, { childList:true, subtree: true });
  3541. }, `let inIFrame = ${inIFrame}`, nullTools)
  3542. };
  3543.  
  3544. scripts['reactor.cc'] = {
  3545. other: ['joyreactor.cc', 'pornreactor.cc'],
  3546. now: () => {
  3547. selectiveEval();
  3548. scriptLander(() => {
  3549. let nt = new nullTools();
  3550. win.open = (function(){ throw new Error('Redirect prevention.'); }).bind(window);
  3551. nt.define(win, 'Worker', function(){});
  3552. nt.define(win, 'JRCH', win.CoinHive);
  3553. }, nullTools);
  3554. },
  3555. click: function(e)
  3556. {
  3557. let node = e.target;
  3558. if (node.nodeType === Node.ELEMENT_NODE &&
  3559. node.style.position === 'absolute' &&
  3560. node.style.zIndex > 0)
  3561. node.parentNode.removeChild(node);
  3562. },
  3563. dom: function()
  3564. {
  3565. let words = new RegExp(
  3566. 'блокировщик рекламы'
  3567. .split('')
  3568. .map(function(e){return e+'[\u200b\u200c\u200d]*';})
  3569. .join('')
  3570. .replace(' ', '\\s*')
  3571. .replace(/[аоре]/g, function(e){return ['[аa]','[оo]','[рp]','[еe]']['аоре'.indexOf(e)];}),
  3572. 'i'),
  3573. can;
  3574. function deeper(spider)
  3575. {
  3576. let c, l, n;
  3577. if (words.test(spider.innerText))
  3578. {
  3579. if (spider.nodeType === Node.TEXT_NODE)
  3580. return true;
  3581. c = spider.childNodes;
  3582. l = c.length;
  3583. n = 0;
  3584. while(l--)
  3585. if (deeper(c[l]), can)
  3586. n++;
  3587. if (n > 0 && n === c.length && spider.offsetHeight < 750)
  3588. can.push(spider);
  3589. return false;
  3590. }
  3591. return true;
  3592. }
  3593. function probe()
  3594. {
  3595. if (words.test(document.body.innerText))
  3596. {
  3597. can = [];
  3598. deeper(document.body);
  3599. let i = can.length, spider;
  3600. while(i--) {
  3601. spider = can[i];
  3602. if (spider.offsetHeight > 10 && spider.offsetHeight < 750)
  3603. _setAttribute.call(spider, 'style', 'background:none!important');
  3604. }
  3605. }
  3606. }
  3607. (new MutationObserver(probe))
  3608. .observe(document, { childList:true, subtree:true });
  3609. }
  3610. };
  3611.  
  3612. scripts['auto.ru'] = () => {
  3613. let words = /Реклама|Яндекс.Директ|yandex_ad_/;
  3614. let userAdsListAds = (
  3615. '.listing-list > .listing-item,'+
  3616. '.listing-item_type_fixed.listing-item'
  3617. );
  3618. let catalogAds = (
  3619. 'div[class*="layout_catalog-inline"],'+
  3620. 'div[class$="layout_horizontal"]'
  3621. );
  3622. let otherAds = (
  3623. '.advt_auto,'+
  3624. '.sidebar-block,'+
  3625. '.pager-listing + div[class],'+
  3626. '.card > div[class][style],'+
  3627. '.sidebar > div[class],'+
  3628. '.main-page__section + div[class],'+
  3629. '.listing > tbody'
  3630. );
  3631. gardener(userAdsListAds, words, {root:'.listing-wrap', observe:true});
  3632. gardener(catalogAds, words, {root:'.catalog__page,.content__wrapper', observe:true});
  3633. gardener(otherAds, words);
  3634. };
  3635.  
  3636. scripts['rsload.net'] = {
  3637. load: () => {
  3638. let dis = document.querySelector('label[class*="cb-disable"]');
  3639. if (dis)
  3640. dis.click();
  3641. },
  3642. click: () => {
  3643. let t = e.target;
  3644. if (t && t.href && (/:\/\/\d+\.\d+\.\d+\.\d+\//.test(t.href)))
  3645. t.href = t.href.replace('://','://rsload.net:rsload.net@');
  3646. }
  3647. };
  3648.  
  3649. let domain;
  3650. // add alternative domain names if present and wrap functions into objects
  3651. for (let name in scripts)
  3652. {
  3653. if (scripts[name] instanceof Function)
  3654. scripts[name] = { now: scripts[name] };
  3655. for (domain of (scripts[name].other||[]))
  3656. {
  3657. if (domain in scripts)
  3658. console.log('Error in scripts list. Script for', name, 'replaced script for', domain);
  3659. scripts[domain] = scripts[name];
  3660. }
  3661. delete scripts[name].other;
  3662. }
  3663. // look for current domain in the list and run appropriate code
  3664. domain = document.domain;
  3665. while (domain.indexOf('.') > -1)
  3666. {
  3667. if (domain in scripts) for (let when in scripts[domain])
  3668. switch(when)
  3669. {
  3670. case 'now':
  3671. scripts[domain][when]();
  3672. break;
  3673. case 'dom':
  3674. document.addEventListener('DOMContentLoaded', scripts[domain][when], false);
  3675. break;
  3676. default:
  3677. document.addEventListener (when, scripts[domain][when], false);
  3678. }
  3679. domain = domain.slice(domain.indexOf('.') + 1);
  3680. }
  3681. })();