RU AdList JS Fixes

try to take over the world!

当前为 2020-01-09 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name RU AdList JS Fixes
  3. // @namespace ruadlist_js_fixes
  4. // @version 20200109.7
  5. // @description try to take over the world!
  6. // @author lainverse & dimisa
  7. // @supportURL https://greasyfork.org/en/scripts/19993-ru-adlist-js-fixes/feedback
  8. // @match *://*/*
  9. // @exclude *://auth.wi-fi.ru/*
  10. // @exclude *://*.alfabank.ru/*
  11. // @exclude *://alfabank.ru/*
  12. // @exclude *://*.unicreditbanking.net/*
  13. // @exclude *://unicreditbanking.net/*
  14. // @exclude *://*.telegram.org/*
  15. // @exclude *://telegram.org/*
  16. // @exclude *://beru.ru/*
  17. // @grant unsafeWindow
  18. // @grant window.close
  19. // @run-at document-start
  20. // ==/UserScript==
  21.  
  22. (function() {
  23. 'use strict';
  24.  
  25. const win = (unsafeWindow || window);
  26.  
  27. // MooTools are crazy enough to replace standard browser object window.Document: https://mootools.net/core
  28. // Occasionally their code runs before my script on some domains and causes all kinds of havoc.
  29. const _Document = Object.getPrototypeOf(HTMLDocument.prototype);
  30. const _Element = Object.getPrototypeOf(HTMLElement.prototype);
  31. // dTree 2.05 in some cases replaces Node object
  32. const _Node = Object.getPrototypeOf(_Element);
  33.  
  34. // http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
  35. const isOpera = (!!window.opr && !!window.opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0,
  36. isChrome = !!window.chrome && !!window.chrome.webstore,
  37. isSafari =
  38. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0 ||
  39. (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window.safari || window.safari.pushNotification);
  40. const isFirefox = 'InstallTrigger' in win;
  41. const inIFrame = (win.self !== win.top);
  42. const _getAttribute = Function.prototype.call.bind(_Element.getAttribute),
  43. _setAttribute = Function.prototype.call.bind(_Element.setAttribute),
  44. _removeAttribute = Function.prototype.call.bind(_Element.removeAttribute);
  45. const _document = win.document,
  46. _de = _document.documentElement,
  47. _appendChild = _Document.appendChild.bind(_de),
  48. _removeChild = _Document.removeChild.bind(_de),
  49. _createElement = _Document.createElement.bind(_document),
  50. _querySelector = _Document.querySelector.bind(_document),
  51. _querySelectorAll = _Document.querySelectorAll.bind(_document);
  52.  
  53. const _console = {};
  54. (_console.initConsole = () => {
  55. for (let name in win.console) _console[name] = console[name];
  56. _console._trace = _console.trace;
  57. _console.trace = (...args) => (_console.groupCollapsed(...args), _console._trace('Stack trace.'), _console.groupEnd());
  58. Object.freeze(_console);
  59. Object.defineProperty(win.console, 'clear', { value: () => null });
  60. })();
  61.  
  62. if (isFirefox && // Exit on image pages in Fx
  63. _document.constructor.prototype.toString() === '[object ImageDocumentPrototype]')
  64. return;
  65.  
  66. // NodeList and HTMLCollection iterator polyfill
  67. // required for old versions of Safari and Chrome 49 (last available for WinXP)
  68. // https://jakearchibald.com/2014/iterators-gonna-iterate/
  69. if (!NodeList.prototype[Symbol.iterator])
  70. NodeList.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
  71. if (!HTMLCollection.prototype[Symbol.iterator])
  72. HTMLCollection.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
  73.  
  74. // Wrapper to run scripts designed to override objects available to other scripts
  75. // Required in old versions of Firefox (<58) or when running with Greasemonkey
  76. let skipLander = true;
  77. try {
  78. skipLander = !(isFirefox && ('StopIteration' in win || GM.info.scriptHandler === 'Greasemonkey'));
  79. } catch(ignore){}
  80. const batchLand = [];
  81. const batchPrepend = new Set();
  82. const _APIString = `const win = window, _console = {}, isFirefox = ${isFirefox}, inIFrame = ${inIFrame}, _document = win.document,`+
  83. `_Document = Object.getPrototypeOf(HTMLDocument.prototype), _Element = Object.getPrototypeOf(HTMLElement.prototype),` +
  84. `_Node = Object.getPrototypeOf(_Element); (${_console.initConsole.toString()})();`
  85. const landScript = (f, pre) => {
  86. let script = _createElement('script');
  87. script.textContent = `(()=>{${_APIString}${[...pre].join(';')};(${f.join(')();(')})();})();`;
  88. _appendChild(script);
  89. _removeChild(script);
  90. };
  91. let scriptLander = f => f();
  92. if (!skipLander) {
  93. scriptLander = (func, ...prepend) => {
  94. prepend.forEach(x => batchPrepend.add(x));
  95. batchLand.push(func);
  96. };
  97. _document.addEventListener(
  98. 'DOMContentLoaded', () => void (scriptLander = (f, ...prep) => landScript([f], prep)), false
  99. );
  100. }
  101.  
  102. function nullTools(opts) {
  103. const nt = this;
  104. opts = opts || {};
  105.  
  106. function Stats(){
  107. const me = this,
  108. updated = new Map(),
  109. logged = new Map();
  110.  
  111. function printUpdated() {
  112. const prepared = [...updated].map(x => {
  113. const [prop, dir] = x;
  114. logged.set(prop, logged.get(prop) | dir);
  115. return `${prop} (${dir ^ (me.GET | me.SET) ? (dir & me.GET ? 'R' : 'W') : 'R/W'})`
  116. }).sort();
  117. updated.clear();
  118. _console.log(`Accessed properties:\n * ${prepared.join('\n * ')}`);
  119. };
  120.  
  121. let logLock;
  122. me.set = async (prop, dir) => {
  123. !(logged.get(prop) & dir) && updated.set(prop, updated.get(prop) | dir);
  124. logLock = (logLock > 0 || !updated.size) ? logLock : setInterval(() => {
  125. printUpdated();
  126. logLock = clearInterval(logLock);
  127. }, 2500);
  128. };
  129. };
  130. Stats.prototype.GET = 1;
  131. Stats.prototype.SET = 2;
  132. const stats = new Stats();
  133.  
  134. const log = async (...args) => opts.log && _console.log(...args);
  135. const objectAlike = x => (x !== null) && typeof x === 'object' || typeof x === 'function';
  136. const parsePath = path => {
  137. let root = win;
  138. let chain = path.split('.');
  139. let link = chain.shift();
  140. for (; chain.length > 0; link = chain.shift()) {
  141. if (!objectAlike(root[link]))
  142. break;
  143. root = root[link];
  144. }
  145. return [root, link, chain];
  146. }
  147.  
  148. nt.destroy = function(o, destroy) {
  149. if (!opts.destroy && !destroy && o instanceof Object)
  150. return;
  151. log('cleaning', o);
  152. try {
  153. for (let item in o) {
  154. if (item instanceof Object)
  155. nt.destroy(item);
  156. delete o[item];
  157. }
  158. } catch (e) {
  159. log('Error in object destructor', e);
  160. }
  161. };
  162.  
  163. nt.define = function(path, val, enumerable = false) {
  164. const [obj, prop, remainder] = parsePath(path);
  165. if (remainder.length) {
  166. _console.warn(`Unable to resolve ${remainder.join('.')} in ${path}`);
  167. return;
  168. }
  169. nt.defineOn(obj, prop, val, path, enumerable);
  170. };
  171.  
  172. nt.defineOn = function(obj, prop, val, path, enumerable = true) {
  173. path = path || ((obj === win) ? prop : `?.${prop}`);
  174. if (path[path.length-1] === '.')
  175. path = `${path}${prop}`;
  176. const desc = Object.getOwnPropertyDescriptor(obj, prop);
  177. if (desc !== undefined && !desc.configurable) {
  178. _console.warn(`Unable to redefine not configurable ${prop} in %o`, obj);
  179. return;
  180. }
  181. Object.defineProperty(
  182. obj, prop, {
  183. get () {
  184. stats.set(path, stats.GET);
  185. return val;
  186. },
  187. set (v) {
  188. stats.set(path, stats.SET);
  189. if (v !== val) {
  190. log(`set ${prop} of`, obj, 'to', v);
  191. nt.destroy(v);
  192. }
  193. },
  194. enumerable: enumerable
  195. }
  196. );
  197. };
  198.  
  199. nt.proxy = function(obj, missingFuncParentName, missingFuncValue) {
  200. return new Proxy(
  201. obj, {
  202. get: (t, p) => {
  203. if (p in t)
  204. return t[p];
  205. if (typeof p === 'symbol') {
  206. if (p === Symbol.toPrimitive)
  207. t[p] = function(hint) {
  208. if (hint === 'string')
  209. return Object.prototype.toString.call(this);
  210. return `[missing toPrimitive] ${name} ${hint}`;
  211. };
  212. else {
  213. t[p] = undefined;
  214. _console.trace(`Missing ${p} in ${missingFuncParentName || '?'} >> %o`, t[p]);
  215. }
  216. return t[p];
  217. }
  218. if (missingFuncParentName) {
  219. t[p] = nt.func(missingFuncValue, `${missingFuncParentName}.${p}`);
  220. return t[p];
  221. }
  222. _console.trace(`Missing ${p} in %o`, t);
  223. },
  224. set: (t, p, v) => {
  225. if (v !== t[p]) {
  226. log('set %s of %o to %o', p, t, v);
  227. nt.destroy(v);
  228. }
  229. return true;
  230. }
  231. }
  232. );
  233. };
  234.  
  235. nt.func = (val, name = '', force_log = false) => nt.proxy(function() {
  236. (force_log || (opts.log || opts.trace)) && _console.trace(`call ${name}(`, ...arguments, `) return`, val);
  237. return val;
  238. });
  239. }
  240. nullTools.toString = new Proxy(nullTools.toString, {
  241. apply: (...args) => Reflect.apply(...args) + ' let nt = new nullTools();'
  242. });
  243. let nt = new nullTools();
  244.  
  245. // Creates and return protected style (unless protection is manually disabled).
  246. // Protected style will re-add itself on removal and remaind enabled on attempt to disable it.
  247. function createStyle(rules, props, skip_protect) {
  248. props = props || {};
  249. props.type = 'text/css';
  250.  
  251. function _protect(style) {
  252. if (skip_protect)
  253. return;
  254.  
  255. Object.defineProperty(style, 'sheet', {
  256. value: null,
  257. enumerable: true
  258. });
  259. Object.defineProperty(style, 'disabled', {
  260. get: () => true, //pretend to be disabled
  261. set: () => undefined,
  262. enumerable: true
  263. });
  264. (new MutationObserver(
  265. (ms) => _removeChild(ms[0].target)
  266. )).observe(style, { childList: true });
  267. }
  268.  
  269.  
  270. function _create() {
  271. let style = _appendChild(_createElement('style'));
  272. Object.assign(style, props);
  273.  
  274. function insertRules(rule) {
  275. if (rule.forEach)
  276. rule.forEach(insertRules);
  277. else try {
  278. style.sheet.insertRule(rule, 0);
  279. } catch (e) {
  280. _console.error(e);
  281. }
  282. }
  283.  
  284. insertRules(rules);
  285. _protect(style);
  286.  
  287. return style;
  288. }
  289.  
  290. let style = _create();
  291. if (skip_protect)
  292. return style;
  293.  
  294. (new MutationObserver(
  295. function(ms) {
  296. let m, node;
  297. let createStyleInANewThread = resolve => setTimeout(
  298. resolve => resolve(_create()),
  299. 0, resolve
  300. );
  301. let setStyle = st => void(style = st);
  302. for (m of ms) for (node of m.removedNodes)
  303. if (node === style)
  304. (new Promise(createStyleInANewThread))
  305. .then(setStyle);
  306. }
  307. )).observe(_de, { childList: true });
  308.  
  309. return style;
  310. }
  311.  
  312. // aborts currently running script with ReferenceError on specific property access
  313. // in case of inline script also checks if it contains specific pattern in it
  314.  
  315. function abortExecutionModule() {
  316. let map = new Map(),
  317. cnt = new Map(),
  318. stack = 0;
  319. const printCounters = (cnts) => {
  320. let s = '';
  321. for (let cntr of cnts)
  322. s += `\n * ${cntr[0]}: ${cntr[1]}`;
  323. return s;
  324. };
  325. const logger = id => {
  326. let { path, mode } = map.get(id);
  327. let prop = `${path} ${mode.toString().replace('Symbol','')}`;
  328. cnt.set(prop, (cnt.get(prop) || 0) + 1);
  329. stack++;
  330. setTimeout(() => {
  331. stack--;
  332. if (!stack)
  333. console.log('Abort execution counters:', printCounters(Array.from(cnt.entries())));
  334. }, 1000);
  335. };
  336. const objectAlike = x => (x !== null) && typeof x === 'object' || typeof x === 'function';
  337. const onAccess = {
  338. Get: Symbol('Read'),
  339. Set: Symbol('Write'),
  340. All: Symbol('Access'),
  341. InlineScript: Symbol('InlineScript')
  342. };
  343. Object.freeze(onAccess);
  344.  
  345. return [onAccess, function abortExecution(mode, path, conf = {}) {
  346. let root = conf.root || win;
  347. let chain = path.split('.');
  348. let postponed = false;
  349. const postpone = (link, chain) => {
  350. postponed = true;
  351. let _val = undefined;
  352. Object.defineProperty(root, link, {
  353. get () { return _val; },
  354. set (val) {
  355. _val = val;
  356. conf.root = val;
  357. conf.fullPath = conf.fullPath || path;
  358. abortExecution(mode, chain.join('.'), conf);
  359. }
  360. });
  361. };
  362. while (chain.length > 1) {
  363. let link = chain.shift();
  364. if (!objectAlike(root[link])) {
  365. if (conf.breakOnMissing)
  366. break;
  367. postpone(link, chain);
  368. break;
  369. }
  370. root = root[link];
  371. }
  372. path = conf.fullPath || path;
  373. if (postponed) {
  374. if (conf.breakOnMissing)
  375. _console.log(`Unable to locate "${path}", abort anchor skipped.`);
  376. return;
  377. }
  378. let target = chain[0];
  379. let des = Object.getOwnPropertyDescriptor(root, target);
  380. if (des && des.get !== undefined) return;
  381. const id = Math.random().toString(36).substr(2);
  382. map.set(id, { path: path, mode: mode });
  383. win.addEventListener('error', e => {
  384. if (e.error && e.error.message === id)
  385. e.stopImmediatePropagation();
  386. }, false);
  387. const get = Symbol('get');
  388. const set = Symbol('set');
  389.  
  390. let check = io => {
  391. if (io === set && mode === onAccess.Get ||
  392. io === get && mode === onAccess.Set)
  393. return;
  394. logger(id);
  395. throw new ReferenceError(id);
  396. };
  397. if (mode === onAccess.InlineScript)
  398. check = () => {
  399. const script = _document.currentScript;
  400. if (script && script.src === '' &&
  401. (!conf.pattern || conf.pattern.test(script.textContent))) {
  402. logger(id);
  403. throw new ReferenceError(id);
  404. }
  405. };
  406.  
  407. let _val = root[target];
  408. Object.defineProperty(root, target, {
  409. get () {
  410. check(get);
  411. return _val;
  412. },
  413. set (v) {
  414. check(set);
  415. _val = v;
  416. }
  417. });
  418. }]
  419. };
  420. abortExecutionModule.toString = function() {
  421. return Function.prototype.toString.call(this) +
  422. ' const [onAccess, abortExecution] = abortExecutionModule();';
  423. };
  424. const [onAccess, abortExecution] = abortExecutionModule();
  425.  
  426. // Fake objects of advertisement networks to break their workflow
  427. // Popular adblock detector
  428. function deployFABStub(root) {
  429. if (!('fuckAdBlock' in root)) {
  430. let FuckAdBlock = function(options) {
  431. let self = this;
  432. self._options = {
  433. checkOnLoad: false,
  434. resetOnEnd: false,
  435. checking: false
  436. };
  437. self.setOption = function(opt, val) {
  438. if (val)
  439. self._options[opt] = val;
  440. else
  441. Object.assign(self._options, opt);
  442. };
  443. if (options)
  444. self.setOption(options);
  445.  
  446. self._var = { event: {} };
  447. self.clearEvent = function() {
  448. self._var.event.detected = [];
  449. self._var.event.notDetected = [];
  450. };
  451. self.clearEvent();
  452.  
  453. self.on = function(detected, fun) {
  454. self._var.event[detected?'detected':'notDetected'].push(fun);
  455. return self;
  456. };
  457. self.onDetected = function(cb) {
  458. return self.on(true, cb);
  459. };
  460. self.onNotDetected = function(cb) {
  461. return self.on(false, cb);
  462. };
  463. self.emitEvent = function() {
  464. for (let fun of self._var.event.notDetected)
  465. fun();
  466. if (self._options.resetOnEnd)
  467. self.clearEvent();
  468. return self;
  469. };
  470. self._creatBait = () => null;
  471. self._destroyBait = () => null;
  472. self._checkBait = function() {
  473. setTimeout((() => self.emitEvent()), 1);
  474. };
  475. self.check = function() {
  476. self._checkBait();
  477. return true;
  478. };
  479.  
  480. let callback = function() {
  481. if (self._options.checkOnLoad)
  482. setTimeout(self.check, 1);
  483. };
  484. root.addEventListener('load', callback, false);
  485. };
  486. nt.defineOn(root, 'FuckAdBlock', FuckAdBlock);
  487. nt.defineOn(root, 'fuckAdBlock', new FuckAdBlock({
  488. checkOnLoad: true,
  489. resetOnEnd: true
  490. }));
  491. }
  492. }
  493. // new version of fAB adapting to fake API
  494. // scriptLander(() => deployFABStub(win), nullTools); // so it's disabled by default for now
  495.  
  496. scriptLander(() => {
  497. // CoinHive miner stub. Continuous 100% CPU load can easily kill some CPU with overheat.
  498. if (!('CoinHive' in win))
  499. if (location.hostname !== 'cnhv.co') {
  500. // CoinHive stub for cases when it doesn't affect site functionality
  501. let CoinHiveConstructor = function() {
  502. _console.log('Fake CoinHive miner created.');
  503. this.setThrottle = nt.func(null);
  504. this.start = nt.func(null);
  505. this.on = nt.func(null);
  506. this.getHashesPerSecond = nt.func(Infinity);
  507. this.getTotalHashes = nt.func(Infinity);
  508. this.getAcceptedHashes = nt.func(Infinity);
  509. };
  510. let CoinHiveStub = nt.proxy({
  511. Anonymous: CoinHiveConstructor,
  512. User: CoinHiveConstructor,
  513. Token: CoinHiveConstructor,
  514. JobThread: nt.func(null),
  515. Res: nt.func(null),
  516. IF_EXCLUSIVE_TAB: false,
  517. CONFIG: nt.proxy({})
  518. });
  519. nt.define('CoinHive', CoinHiveStub);
  520. } else {
  521. // CoinHive wrapper to fool sites which expect it to actually work and return results
  522. let CoinHiveObject;
  523. Object.defineProperty(win, 'CoinHive', {
  524. set: function(obj) {
  525. if ('Token' in obj) {
  526. _console.log('[CoinHive] Token wrapper applied.');
  527. let _Token = obj.Token.bind(obj);
  528. obj.Token = function(siteKey, goal, params) {
  529. let _goal = goal;
  530. goal = goal > 256 ? 256 : goal;
  531. _console.log(`[CoinHive] Original goal: ${_goal}, new smaller goal ${goal}.`);
  532. _console.log(`With smaller goals server may return 'invalid_goal' error and stop working.`);
  533. let miner = _Token(siteKey, goal, params);
  534. miner.setThrottle(0.99);
  535. miner.setThrottle = () => null;
  536. let _start = miner.start.bind(miner);
  537. miner.start = function() {
  538. let res = _start(window.CoinHive.FORCE_EXCLUSIVE_TAB);
  539. return res;
  540. };
  541. let _getTotalHashes = miner.getTotalHashes;
  542. miner.getTotalHashes = function() {
  543. return Math.trunc(_getTotalHashes.call(this) / goal * _goal);
  544. };
  545. let __emit = miner._emit;
  546. miner._emit = function(state, props) {
  547. let _self = this;
  548. _console.log('[CoinHive] state: %o %o', state, props);
  549. if (state === 'job')
  550. setTimeout(() => {
  551. _self.stop();
  552. _self._emit('accepted', { hashes: goal });
  553. }, 1000);
  554. return __emit.apply(_self, arguments);
  555. };
  556. let _on = miner.on.bind(miner);
  557. miner.on = function(type, callback) {
  558. if (type === 'accepted') {
  559. _console.log('[CoinHive] "accepted" callback wrapper applied.');
  560. let _callback = callback;
  561. callback = function(params) {
  562. _console.log('[CoinHive] "accepted" callback is called, imitating original goal being reached.');
  563. params.hashes = _goal;
  564. return _callback.apply(this, arguments);
  565. };
  566. miner.stop();
  567. }
  568. return _on(type, callback);
  569. };
  570. return miner;
  571. };
  572. }
  573. CoinHiveObject = obj;
  574. },
  575. get: () => CoinHiveObject
  576. });
  577. }
  578.  
  579. // VideoJS player wrapper
  580. VideoJS: {
  581. let _videojs = win.videojs || undefined;
  582. Object.defineProperty(win, 'videojs', {
  583. get: () => _videojs,
  584. set: f => {
  585. if (f === _videojs)
  586. return true;
  587. _console.log('videojs = %o', f);
  588. _videojs = new Proxy(f, {
  589. apply: (tgt, ths, args) => {
  590. _console.log('videojs(', ...args, ')');
  591. let params = args[1];
  592. if (params) {
  593. if (params.hasAd)
  594. params.hasAd = false;
  595. if (params.plugins && params.plugins.vastClient)
  596. delete params.plugins.vastClient;
  597. }
  598. let res = Reflect.apply(tgt, ths, args);
  599. if (res) {
  600. if (params && params.autoplay && res.on && res.off) {
  601. let autoplayHandler = () => {
  602. setTimeout(() => {
  603. let button = _querySelector('.vjs-play-control.vjs-playing');
  604. if (button)
  605. button.click();
  606. }, 0);
  607. _console.log('videojs autoplay prevention');
  608. res.off('playing', autoplayHandler);
  609. };
  610. res.on('playing', autoplayHandler);
  611. }
  612. if (res.seed)
  613. res.seed = () => null;
  614. }
  615. _console.log('player = %o', res);
  616. return res;
  617. }
  618. });
  619. }
  620. });
  621. }
  622.  
  623. // Set a little trap for BodyClick ads
  624. abortExecution(onAccess.Set, '__BC_domain');
  625.  
  626. // Yandex API (ADBTools, Metrika)
  627. let hostname = location.hostname;
  628. if (// Thank you, Greasemonkey, now I have to check for this. -_-
  629. location.protocol === 'about:' ||
  630. // Google likes to define odd global variables like Ya
  631. hostname.startsWith('google.') || hostname.includes('.google.') ||
  632. // Also, Yandex uses their Ya object for a lot of things on their pages and
  633. // wrapping it may cause problems. It's better to skip it in some cases.
  634. ((hostname.startsWith('yandex.') || hostname.includes('.yandex.')) &&
  635. /^\/((yand)?search|images)/i.test(location.pathname) && !hostname.startsWith('news.')) ||
  636. // Also skip on these following sites since they use
  637. // code minification which generated global Ya variable.
  638. hostname.endsWith('chatango.com') || hostname.endsWith('github.io') ||
  639. hostname.endsWith('grimtools.com') || hostname.endsWith('poeplanner.com'))
  640. return;
  641.  
  642. let YaProps = new Set();
  643. function setObfuscatedProperty(Ya, rootProp, obj, name) {
  644. if (YaProps.has(rootProp))
  645. return;
  646. _console.trace(`Ya.${rootProp} = Ya.${name}`);
  647. nt.defineOn(Ya, rootProp, Ya[name], 'Ya.');
  648. YaProps.add(rootProp);
  649. for (let prop in obj)
  650. delete obj[prop];
  651. for (let prop in Ya[name])
  652. obj[prop] = Ya[name][prop];
  653. }
  654. function onObfuscatedProperty (Ya, rootProp, obj) {
  655. if ('AdvManager' in obj || 'AdvManagerStatic' in obj || 'isAllowedRepeatAds' in obj) {
  656. setObfuscatedProperty(Ya, rootProp, obj, 'Context');
  657. return Ya.Context;
  658. }
  659. if ('create' in obj && 'createAdaptive' in obj && 'createScroll' in obj) {
  660. setObfuscatedProperty(Ya, rootProp, obj, 'adfoxCode');
  661. return Ya.adfoxCode;
  662. }
  663. return new Proxy(obj, {
  664. set: (tgt, prop, val) => {
  665. if (prop === 'AdvManager' || prop === 'isAllowedRepeatAds') {
  666. setObfuscatedProperty(Ya, rootProp, obj, 'Context');
  667. return true;
  668. }
  669. if (prop === 'create' && 'createAdaptive' in obj && 'createScroll' in obj ||
  670. prop === 'createScroll' && 'create' in obj && 'createAdaptive' in obj ||
  671. prop === 'createAdaptive' && 'create' in obj && 'createScroll' in obj) {
  672. setObfuscatedProperty(Ya, rootProp, obj, 'adfoxCode');
  673. return true;
  674. }
  675. tgt[prop] = val;
  676. return true;
  677. },
  678. get: (tgt, prop) => {
  679. if (prop === 'AdvManager' && !(prop in tgt)) {
  680. _console.trace(`Injected missing ${prop} in Ya.${rootProp}.`);
  681. tgt[prop] = Ya.Context[prop];
  682. }
  683. return tgt[prop];
  684. }
  685. });
  686. }
  687. let Rum = {};
  688. [
  689. '__timeMarks', '_timeMarks', '__deltaMarks', '_deltaMarks',
  690. '__defRes', '_defRes', '__defTimes', '_defTimes', '_vars',
  691. 'commonVars'
  692. ].forEach(name => void(Rum[name] = []));
  693. [
  694. 'getSettings', 'getVarsList'
  695. ].forEach(name => void(Rum[name] = nt.func([], `Ya.Rum.${name}`)));
  696. [
  697. ['ajaxStart', 0], ['ajaxComplete', 0],
  698. ['enabled', true], ['_tti', null],
  699. ['vsChanged', false], ['vsStart', 'visible']
  700. ].forEach(([prop, val]) => void(Rum[prop] = val));
  701. Rum = nt.proxy(Rum, 'Ya.Rum', null);
  702. let Ya = new Proxy({}, {
  703. set: function(tgt, prop, val) {
  704. if (val === tgt[prop])
  705. return true;
  706. if (prop === 'Rum') {
  707. nt.defineOn(tgt, prop, Rum, 'Ya.');
  708. YaProps.add(prop);
  709. Object.assign(val, Rum);
  710. }
  711. if (YaProps.has(prop)) {
  712. _console.log(`Ya.${prop} \u2260 %o`, val);
  713. return true;
  714. }
  715. if (typeof val === 'object' && prop !== '__inline_params__' && !('length' in val))
  716. val = onObfuscatedProperty(Ya, prop, val);
  717. tgt[prop] = val;
  718. _console.log(`Ya.${prop} = %o`, val);
  719. return true;
  720. },
  721. get: (tgt, prop) => tgt[prop]
  722. });
  723. let callWithParams = function(f) {
  724. f.call(this, Ya.__inline_params__ || {});
  725. Ya.__inline_params__ = null;
  726. };
  727. nt.defineOn(Ya, 'callWithParams', callWithParams, 'Ya.');
  728. nt.defineOn(Ya, 'PerfCounters', nt.proxy({
  729. __cacheEvents: []
  730. }, 'Ya.PerfCounters', null), 'Ya.');
  731. nt.defineOn(Ya, '__isSent', true, 'Ya.');
  732. nt.defineOn(Ya, 'confirmUrl', '', 'Ya.');
  733. nt.defineOn(Ya, 'Direct', nt.proxy({}, 'Ya.Direct', null), 'Ya.');
  734. nt.defineOn(Ya, 'mediaCode', nt.proxy({
  735. create: function() {
  736. if (inIFrame) {
  737. _console.log('Removed body of ad-frame.');
  738. _document.documentElement.removeChild(_document.body);
  739. }
  740. }
  741. }, 'Ya.mediaCode', null), 'Ya.');
  742. let extra = nt.proxy({
  743. extra: nt.proxy({ match: 0, confirm: '', src: '' }),
  744. id: 0, percent: 100, threshold: 1
  745. });
  746. nt.defineOn(Ya, '_exp', nt.proxy({
  747. id: 0, coin: 0,
  748. choose: nt.func(extra),
  749. get: (prop) => extra.hasOwnProperty(prop) ? extra[prop] : null,
  750. getId: nt.func(0),
  751. defaultVersion: extra,
  752. getExtra: nt.func(extra.extra),
  753. getDefaultExtra: nt.func(extra.extra),
  754. versions: [extra]
  755. }), 'Ya.');
  756. nt.defineOn(Ya, 'c', nt.func(null), 'Ya.');
  757. nt.defineOn(Ya, 'ADBTools', function(){
  758. this.getCurrentState = nt.func(true);
  759. return nt.proxy(this, 'Ya.ADBTools', null);
  760. }, 'Ya.');
  761. nt.defineOn(Ya, 'AdDetector', nt.proxy({}, 'Ya.AdDetector', null), 'Ya.');
  762. let definePr = o => {
  763. Object.defineProperty(o, 'pr', {
  764. get: () => Math.floor(Math.random() * 1e6) + 1,
  765. set: () => true
  766. });
  767. };
  768. let adfoxCode = {
  769. forcedDirectLoadingExp: nt.proxy({ isLoadingTurnedOn: false, isExp: false }),
  770. isLoadingTurnedOn: false,
  771. xhrExperiment: nt.proxy({ isXhr: true, isControl: true }),
  772. matchidManager: nt.proxy({}, 'Ya.adfoxCode.matchidManager', null),
  773. _: []
  774. };
  775. definePr(adfoxCode);
  776. [
  777. 'clearSession', 'create', 'createAdaptive', 'createScroll',
  778. 'destroy', 'moduleLoad', 'reload', 'setModule'
  779. ].forEach(name => void(adfoxCode[name] = nt.func(null, `Ya.adfoxCode.${name}`)));
  780. nt.defineOn(Ya, 'adfoxCode', nt.proxy(adfoxCode, 'Ya.adfoxCode', null), 'Ya.');
  781. let managerForAdfox = {
  782. loaderVersion: 1,
  783. isCurrrencyExp: true,
  784. isReady: nt.func(true, 'Ya.headerBidding.managerForAdfox.isReady'),
  785. getRequestTimeout: nt.func(300 + Math.floor(Math.random()*100), 'Ya.headerBidding.managerForAdfox.getRequestTimeout')
  786. };
  787. let headerBidding = nt.proxy({
  788. setSettings: opts => {
  789. if (!(opts && opts.adUnits))
  790. return null;
  791. let ids = [];
  792. for (let unit of opts.adUnits)
  793. ids.push(unit.code);
  794. createStyle(`#${ids.join(', #')} { display: none !important }`);
  795. },
  796. pushAdUnits: nt.func(null, 'Ya.headerBidding.pushAdUnits'),
  797. managerForAdfox: nt.proxy(managerForAdfox, 'Ya.headerBidding.managerForAdfox', null)
  798. });
  799. definePr(headerBidding);
  800. nt.defineOn(Ya, 'headerBidding', headerBidding, 'Ya.');
  801.  
  802. let AdvManager = function() {
  803. this.render = function(o) {
  804. if (!o.renderTo)
  805. return;
  806. let placeholder = _document.getElementById(o.renderTo);
  807. if (!placeholder)
  808. return _console.warn('Ya.AdvManager.render call w/o placeholder %o', o);
  809. let parent = placeholder.parentNode;
  810. placeholder.style = 'display:none!important';
  811. parent.style = (parent.getAttribute('style')||'') + 'height:auto!important';
  812. // fix for Yandex TV pages
  813. if (location.hostname.startsWith('tv.yandex.')) {
  814. let sibling = placeholder.previousSibling;
  815. if (sibling && sibling.classList && sibling.classList.contains('tv-spin'))
  816. sibling.style.display = 'none';
  817. }
  818. };
  819. this.constructor = Object;
  820. return nt.proxy(this, 'Ya.AdvManager', null);
  821. };
  822. let _Ya_Context_undefined_count = {};
  823. nt.defineOn(Ya, 'Context', new Proxy({
  824. __longExperiment: null,
  825. _callbacks: nt.proxy([]),
  826. _asyncModeOn: true,
  827. _init: nt.func(null),
  828. _load_callbacks: nt.proxy([]),
  829. performanceStorage: nt.proxy({}),
  830. processCallbacks: nt.func(null),
  831. isAllowedRepeatAds: nt.func(null),
  832. isNewLoader: nt.func(false),
  833. getItem: nt.func(null),
  834. AdvManager: new AdvManager(),
  835. AdvManagerStatic: new AdvManager()
  836. }, {
  837. get: (ctx, prop) => {
  838. if (prop in ctx)
  839. return ctx[prop];
  840. if (prop in _Ya_Context_undefined_count)
  841. _Ya_Context_undefined_count[prop]++;
  842. else {
  843. _Ya_Context_undefined_count[prop] = 1;
  844. _console.trace(`Mising '${prop}' in Ya.Context`);
  845. }
  846. if (_Ya_Context_undefined_count[prop] >= 5) {
  847. _console.trace(`Ya.Context.${prop} = Ya.Context.AdvManager`);
  848. ctx[prop] = ctx.AdvManager;
  849. }
  850. },
  851. set: () => true
  852. }), 'Ya.');
  853. let Metrika = function Metrika(x) {
  854. this._ecommerce = '';
  855. if (x && 'id' in x)
  856. this.id = x.id;
  857. else
  858. this.id = 0;
  859. return nt.proxy(this, 'Ya.Metrika', null);
  860. };
  861. Metrika.counters = () => Ya._metrika.counters;
  862. nt.defineOn(Ya, 'Metrika', Metrika, 'Ya.');
  863. nt.defineOn(Ya, 'Metrika2', Metrika, 'Ya.');
  864. let counter = new Metrika();
  865. nt.defineOn(Ya, '_metrika', nt.proxy({
  866. counter: counter,
  867. counters: [counter],
  868. hitParam: {},
  869. counterNum: 0,
  870. hitId: 0,
  871. v: 1,
  872. i: 0,
  873. _globalMetrikaHitId: 0,
  874. getCounters: null,
  875. dataLayer: null,
  876. f1: null
  877. }), 'Ya.');
  878. nt.defineOn(Ya, '_globalMetrikaHitId', 0, 'Ya.');
  879. counter = {};
  880. [
  881. 'stringifyParams','_getVars',
  882. 'getUid','getUrl','getHash'
  883. ].forEach(name => void(counter[name] = nt.func('', `Ya.counter.${name}`)));
  884. nt.defineOn(Ya, 'counter', nt.proxy(counter, 'Ya.counter', null), 'Ya.');
  885. nt.defineOn(Ya, 'jserrors', [], 'Ya.');
  886. nt.defineOn(Ya, 'onerror', nt.func(null, 'Ya.onerror'), 'Ya.');
  887. let error_on_access = false;
  888. if ('Ya' in win)
  889. try {
  890. _console.log('Found existing Ya object: %o', win.Ya);
  891. for (let prop in win.Ya)
  892. Ya[prop] = win.Ya[prop];
  893. } catch(ignore) {
  894. error_on_access = true;
  895. }
  896. if (!error_on_access && // some people don't know how to export only necessary stuff into global context
  897. location.hostname !== 'material.io') { // so, here is an exception for one of such cases
  898. for (let prop in Ya)
  899. if (prop !== '__inline_params__')
  900. YaProps.add(prop);
  901. nt.define('Ya', Ya);
  902. } else
  903. _console.warn('Looks like window.Ya blocked with error-on-access scriptlet.');
  904. // Yandex.Metrika callbacks
  905. let yandex_metrika_callbacks = [];
  906. _document.addEventListener(
  907. 'DOMContentLoaded', () => {
  908. yandex_metrika_callbacks.forEach((f) => f && f.call(window));
  909. yandex_metrika_callbacks.length = 0;
  910. yandex_metrika_callbacks.push = (f) => setTimeout(f, 0);
  911. }, false
  912. );
  913. nt.define('yandex_metrika_callbacks', yandex_metrika_callbacks);
  914. }, nullTools, createStyle, abortExecutionModule);
  915.  
  916. if (!isFirefox) {
  917. // scripts for non-Firefox browsers
  918. // https://greasyfork.org/scripts/14720-it-s-not-important
  919. unimptt: {
  920. // BigInt were implemented in Chrome 67 which also support
  921. // proper user styles and doesn't need this fix anymore.
  922. if ((isChrome || isOpera) && 'BigInt' in win)
  923. break unimptt;
  924.  
  925. let imptt = /((display|(margin|padding)(-top|-bottom)?)\s*:[^;!]*)!\s*important/ig,
  926. ret_b = (a,b) => b,
  927. _toLowerCase = String.prototype.toLowerCase,
  928. protectedNodes = new WeakSet(),
  929. log = false;
  930.  
  931. let logger = function() {
  932. if (log)
  933. _console.log('Some page elements became a bit less important.');
  934. log = false;
  935. };
  936.  
  937. let unimportanter = function(node) {
  938. let style = (node.nodeType === _Node.ELEMENT_NODE) ?
  939. _getAttribute(node, 'style') : null;
  940.  
  941. if (!style || !imptt.test(style) || node.style.display === 'none' ||
  942. (node.src && node.src.startsWith('chrome-extension:'))) // Web of Trust IFRAME and similar
  943. return false; // get out if we have nothing to do here
  944.  
  945. protectedNodes.add(node);
  946. _setAttribute(node, 'style', style.replace(imptt, ret_b));
  947. log = true;
  948. };
  949.  
  950. (new MutationObserver(
  951. function(mutations) {
  952. setTimeout(
  953. function(ms) {
  954. let m, node;
  955. for (m of ms) for (node of m.addedNodes)
  956. unimportanter(node);
  957. logger();
  958. }, 0, mutations
  959. );
  960. }
  961. )).observe(_document, {
  962. childList : true,
  963. subtree : true
  964. });
  965.  
  966. const _apply = Reflect.apply;
  967. _Element.setAttribute = new Proxy(_Element.setAttribute, {
  968. apply: (fun, that, args) => {
  969. if (args[0] && _toLowerCase.call(args[0]) === 'style' && protectedNodes.has(that)) {
  970. let value = args[1].replace(imptt, ret_b);
  971. log = (args[1] !== value);
  972. logger();
  973. args[1] = value;
  974. }
  975. return _apply(fun, that, args);
  976. }
  977. });
  978.  
  979. win.addEventListener (
  980. 'load', () => {
  981. for (let imp of _querySelectorAll('[style*="!"]'))
  982. unimportanter(imp);
  983. logger();
  984. }, false
  985. );
  986. }
  987.  
  988. // Naive ABP Style protector
  989. if ('ShadowRoot' in win) {
  990. let _removeChild = Function.prototype.call.bind(_Node.removeChild);
  991. let _appendChild = Function.prototype.call.bind(_Node.appendChild);
  992. let createShadow = () => _createElement('shadow');
  993. // Prevent adding fake content entry point
  994. let _apply = Reflect.apply;
  995. _Node.appendChild = new Proxy(_Node.appendChild, {
  996. apply: (fun, that, args) => {
  997. if (that instanceof ShadowRoot &&
  998. args[0] instanceof HTMLContentElement)
  999. args[1] = createShadow();
  1000. return _apply(fun, that, args);
  1001. }
  1002. });
  1003. {
  1004. let _shadowSelector = Function.prototype.call.bind(ShadowRoot.prototype.querySelector);
  1005. let _innerHTML = Object.getOwnPropertyDescriptor(ShadowRoot.prototype, 'innerHTML');
  1006. let _parentNode = Object.getOwnPropertyDescriptor(_Node, 'parentNode');
  1007. if (_innerHTML && _parentNode) {
  1008. let _set = Function.prototype.call.bind(_innerHTML.set);
  1009. let _getParent = Function.prototype.call.bind(_parentNode.get);
  1010. _innerHTML.configurable = false;
  1011. _innerHTML.set = function() {
  1012. _set(this, ...arguments);
  1013. let content = _shadowSelector(this, 'content');
  1014. if (content) {
  1015. let parent = _getParent(content);
  1016. _removeChild(parent, content);
  1017. _appendChild(parent, createShadow());
  1018. }
  1019. };
  1020. }
  1021. Object.defineProperty(ShadowRoot.prototype, 'innerHTML', _innerHTML);
  1022. }
  1023. // Locate and apply extra protection to a style on top of what ABP does
  1024. let style;
  1025. (new Promise(
  1026. function(resolve, reject) {
  1027. let getStyle = () => _querySelector('::shadow style');
  1028. style = getStyle();
  1029. if (style)
  1030. return resolve(style);
  1031. let intv = setInterval(
  1032. function() {
  1033. style = getStyle();
  1034. if (!style)
  1035. return;
  1036. intv = clearInterval(intv);
  1037. return resolve(style);
  1038. }, 0
  1039. );
  1040. _document.addEventListener(
  1041. 'DOMContentLoaded', () => {
  1042. if (intv)
  1043. clearInterval(intv);
  1044. style = getStyle();
  1045. return style ? resolve(style) : reject();
  1046. }, false
  1047. );
  1048. }
  1049. )).then(
  1050. function(style) {
  1051. let emptyArr = [],
  1052. nullStr = {
  1053. get: () => '',
  1054. set: () => undefined
  1055. };
  1056. let shadow = style.parentNode;
  1057. Object.defineProperties(shadow, {
  1058. childElementCount: { value: 0 },
  1059. styleSheets: { value: emptyArr },
  1060. firstChild: { value: null },
  1061. firstElementChild: { value: null },
  1062. lastChild: { value: null },
  1063. lastElementChild: { value: null },
  1064. childNodes: { value: emptyArr },
  1065. children: { value: emptyArr },
  1066. innerHTML: { value: nullStr },
  1067. });
  1068. Object.defineProperties(style, {
  1069. innerHTML: { value: nullStr },
  1070. textContent: { value: nullStr },
  1071. ownerDocument: { value: null },
  1072. parentNode: {value: null },
  1073. previousElementSibling: { value: null },
  1074. previousSibling: { value: null },
  1075. disabled: { get: () => true, set: () => null }
  1076. });
  1077. Object.defineProperties(style.sheet, {
  1078. deleteRule: { value: () => null },
  1079. disabled: { get: () => true, set: () => null },
  1080. cssRules: { value: emptyArr },
  1081. rules: { value: emptyArr }
  1082. });
  1083. }
  1084. ).catch(()=>null);
  1085. _Node.removeChild = new Proxy(_Node.removeChild, {
  1086. apply: (fun, that, args) => {
  1087. if (args[0] === style)
  1088. return;
  1089. return _apply(fun, that, args);
  1090. }
  1091. });
  1092. }
  1093. }
  1094.  
  1095. if (/^https?:\/\/(mail\.yandex\.|music\.yandex\.|(www\.)?yandex\.[^/]+\/(yand)?search[/?])/i.test(win.location.href) ||
  1096. /^https?:\/\/tv\.yandex\./i.test(win.location.href)) {
  1097. // https://greasyfork.org/en/scripts/809-no-yandex-ads
  1098. const yadWord = /Яндекс.Директ/i,
  1099. adWords = /Реклама|Ad/i;
  1100. // Function to attach an observer to monitor dynamic changes on the page
  1101. let pageUpdateObserver = (func, obj, params) => {
  1102. if (obj)
  1103. (new MutationObserver(func))
  1104. .observe(obj, (params || { childList:true, subtree:true }));
  1105. };
  1106. // Short name for parentNode.removeChild and setAttribute style to display:none
  1107. let remove = node => {
  1108. if (!node || !node.parentNode)
  1109. return false;
  1110. _console.log('Removed node.');
  1111. node.parentNode.removeChild(node);
  1112. };
  1113. let hide = node => {
  1114. if (!node)
  1115. return false;
  1116. _console.log('Hid node.');
  1117. _setAttribute(node, 'style', 'display:none!important');
  1118. };
  1119. // Yandex Mail ads
  1120. if (location.hostname.startsWith('mail.')) {
  1121. let wrap = vl => {
  1122. if (!vl)
  1123. return vl;
  1124. _console.log('Daria = %o', vl);
  1125. nt.defineOn(vl, 'AdBlock', nt.proxy({
  1126. detect: nt.func(new Promise(() => null), 'Daria.AdBlock.detect'),
  1127. enabled: false
  1128. }), 'Daria.');
  1129. nt.defineOn(vl, 'AdvPresenter', nt.proxy({
  1130. _config: nt.proxy({
  1131. banner: false,
  1132. done: false,
  1133. line: false
  1134. })
  1135. }), 'Daria.');
  1136. if (vl.Config) {
  1137. delete vl.Config.adBlockDetector;
  1138. delete vl.Config['adv-url'];
  1139. delete vl.Config.cryprox;
  1140. if (vl.Config.features) {
  1141. delete vl.Config.features.web_adloader_with_cookie_cache;
  1142. delete vl.Config.features.web_ads;
  1143. delete vl.Config.features.web_ads_mute;
  1144. }
  1145. vl.Config.mayHaveAdv = false;
  1146. }
  1147. return vl;
  1148. };
  1149. let _Daria = wrap(win.Daria);
  1150. if (_Daria)
  1151. _console.log('Wrapped already existing object "Daria".');
  1152. Object.defineProperty(win, 'Daria', {
  1153. get: () => _Daria,
  1154. set: vl => {
  1155. if (vl === _Daria)
  1156. return;
  1157. _Daria = wrap(vl);
  1158. }
  1159. });
  1160. }
  1161. // prevent/defuse adblock detector and cleanup localStorage
  1162. for (let name in localStorage)
  1163. if (name.startsWith('videoplayer-ad-session-') ||
  1164. ['ic', 'yu', 'ludca', 'test'].includes(name))
  1165. localStorage.removeItem(name);
  1166. nt.define('localStorage._mt__data', '');
  1167. nt.define('localStorage.yandexJSPlayerApiSavedSingleVideoSessionWatchedTimeSinceAd', Math.random() * 1000);
  1168. // cookie cleaner
  1169. let yp_keepCookieParts = /\.(sp|ygo|ygu)\./; // ygo = city id; ygu = detect city automatically
  1170. let _doc_proto = ('cookie' in _Document) ? _Document : Object.getPrototypeOf(_document);
  1171. let _cookie = Object.getOwnPropertyDescriptor(_doc_proto, 'cookie');
  1172. if (_cookie) {
  1173. let _set_cookie = Function.prototype.call.bind(_cookie.set);
  1174. _cookie.set = function(value) {
  1175. if (/^(mda=|yp=|ys=|yabs-|__|bltsr=)/.test(value))
  1176. // remove value, set expired
  1177. if (!value.startsWith('yp=')) {
  1178. value = value.replace(/^([^=]+=)[^;]+/,'$1').replace(/(expires=)[\w\s\d,]+/,'$1Thu, 01 Jan 1970 00');
  1179. _console.log('expire cookie %o', value.match(/^[^=]+/)[0]);
  1180. } else {
  1181. let parts = value.split(';');
  1182. let values = parts[0].split('#').filter(part => yp_keepCookieParts.test(part));
  1183. if (values.length)
  1184. values[0] = values[0].replace(/^yp=/, '');
  1185. let res = `yp=${values.join('#')}`;
  1186. _console.log(`set cookie ${res}, dropped ${parts[0].replace(res,'')}`);
  1187. parts[0] = res;
  1188. value = parts.join(';');
  1189. }
  1190. return _set_cookie(this, value);
  1191. };
  1192. Object.defineProperty(_doc_proto, 'cookie', _cookie);
  1193. }
  1194. // other ads
  1195. _document.addEventListener(
  1196. 'DOMContentLoaded', () => {
  1197. {
  1198. // Generic ads removal and fixes
  1199. let node = _querySelector('.serp-header');
  1200. if (node)
  1201. node.style.marginTop = '0';
  1202. for (node of _querySelectorAll(
  1203. '.serp-adv__head + .serp-item,'+
  1204. '#adbanner,'+
  1205. '.serp-adv,'+
  1206. '.b-spec-adv,'+
  1207. 'div[class*="serp-adv__"]:not(.serp-adv__found):not(.serp-adv__displayed)'
  1208. )) remove(node);
  1209. }
  1210. // Search ads
  1211. function removeSearchAds() {
  1212. for (let node of _querySelectorAll('.serp-item'))
  1213. if (_getAttribute(node, 'role') === 'complementary' ||
  1214. adWords.test((node.querySelector('.label')||{}).textContent))
  1215. hide(node);
  1216. }
  1217. // Music ads
  1218. function removeMusicAds() {
  1219. for (let node of _querySelectorAll('.ads-block'))
  1220. remove(node);
  1221. }
  1222. // TV fixes
  1223. function removeTVAds() {
  1224. for (let node of _querySelectorAll('div[class^="_"][data-reactid] > div'))
  1225. if (yadWord.test(node.textContent) || node.querySelector('iframe:not([src])')) {
  1226. if (node.offsetWidth) {
  1227. let pad = _document.createElement('div');
  1228. _setAttribute(pad, 'style', `width:${node.offsetWidth}px`);
  1229. node.parentNode.appendChild(pad);
  1230. }
  1231. remove(node);
  1232. }
  1233. }
  1234.  
  1235. if (location.hostname.startsWith('music.')) {
  1236. pageUpdateObserver(removeMusicAds, _querySelector('.sidebar'));
  1237. removeMusicAds();
  1238. } else if (location.hostname.startsWith('tv.')) {
  1239. pageUpdateObserver(removeTVAds, _document.body);
  1240. removeTVAds();
  1241. } else if (!location.hostname.startsWith('mail.')) {
  1242. pageUpdateObserver(removeSearchAds, _querySelector('.main__content'));
  1243. removeSearchAds();
  1244. }
  1245. }
  1246. );
  1247. }
  1248.  
  1249. // Yandex Raven stub (some monitoring sub-system)
  1250. function yandexRavenStub() {
  1251. let nt = new nullTools({ log: true });
  1252. nt.define('Raven', nt.proxy({
  1253. context: f => f(),
  1254. config: nt.func(
  1255. nt.proxy(
  1256. {}, 'Raven.config',
  1257. nt.proxy({}, 'Raven.config()..', null)
  1258. ), 'Raven.config')
  1259. }, 'Raven', null));
  1260. }
  1261.  
  1262. // Generic Yandex Scripts
  1263. if (/^https?:\/\/([^.]+\.)*yandex\.[^/]+/i.test(win.location.href)) {
  1264. // remove banner on the start page
  1265. // ads on afisha.yandex.ru, however it looks like selectiveEval isn't perfect
  1266. // since eval could be called in scope to access properties of that scope and
  1267. // such calls with it active break functionality on metrika.yandex.ru
  1268. scriptLander(() => {
  1269. if (win.location.hostname === 'afisha.yandex.ru')
  1270. selectiveEval(/AdvManagerStatic/);
  1271. selectiveCookies();
  1272. let nt = new nullTools({log: false, trace: true});
  1273. let AwapsJsonAPI_Json = function(...args) {
  1274. _console.log('>> new AwapsJsonAPI.Json(', ...args, ')');
  1275. };
  1276. [
  1277. 'setID', 'addImageContent', 'sendCounts',
  1278. 'drawBanner', 'bannerIsInvisible', 'expand', 'refreshAd'
  1279. ].forEach(name => void(AwapsJsonAPI_Json.prototype[name] = nt.func(null, `AwapsJsonAPI.Json.${name}`)));
  1280. AwapsJsonAPI_Json.prototype.checkBannerVisibility = nt.func(true, 'AwapsJsonAPI.Json.checkBannerVisibility');
  1281. AwapsJsonAPI_Json.prototype.addIframeContent = nt.proxy(function(...args) {
  1282. try {
  1283. let frame = args[1][0].parentNode;
  1284. frame.parentNode.removeChild(frame);
  1285. _console.log(`Removed banner placeholder.`);
  1286. } catch(ignore) {
  1287. _console.log(`Can't locate frame object to remove.`);
  1288. }
  1289. });
  1290. AwapsJsonAPI_Json.prototype.getHTML = nt.func('', 'AwapsJsonAPI.Json.getHTML');
  1291. AwapsJsonAPI_Json.prototype = nt.proxy(AwapsJsonAPI_Json.prototype);
  1292. AwapsJsonAPI_Json = nt.proxy(AwapsJsonAPI_Json);
  1293. if ('AwapsJsonAPI' in win) {
  1294. _console.log('Oops! AwapsJsonAPI already defined.');
  1295. let f = win.AwapsJsonAPI.Json;
  1296. win.AwapsJsonAPI.Json = AwapsJsonAPI_Json;
  1297. if (f && f.prototype)
  1298. f.prototype = AwapsJsonAPI_Json.prototype;
  1299. } else
  1300. nt.define('AwapsJsonAPI', nt.proxy({
  1301. Json: AwapsJsonAPI_Json
  1302. }));
  1303.  
  1304. let parseExport = x => {
  1305. if (!x)
  1306. return x;
  1307. // remove banner placeholder
  1308. if (x.banner && x.banner.cls && x.banner.cls.banner__parent) {
  1309. let hide = pattern => {
  1310. for (let banner of _document.querySelectorAll(pattern)) {
  1311. _setAttribute(banner, 'style', 'display:none!important');
  1312. _console.log('Hid banner placeholder.');
  1313. }
  1314. }
  1315. let _parent = `.${x.banner.cls.banner__parent}`;
  1316. hide(_parent);
  1317. _document.addEventListener('DOMContentLoaded', () => hide(_parent), false);
  1318. }
  1319.  
  1320. // remove banner data and some other stuff
  1321. delete x.banner;
  1322. delete x.consistency;
  1323. delete x['i-bannerid'];
  1324. delete x['i-counter'];
  1325. delete x['promo-curtain'];
  1326.  
  1327. // remove parts of ga-counter (complete removal break "ТВ Онлайн")
  1328. if (x['ga-counter'] && x['ga-counter'].data) {
  1329. x['ga-counter'].data.id = 0;
  1330. delete x['ga-counter'].data.ether;
  1331. delete x['ga-counter'].data.iframeSrc;
  1332. delete x['ga-counter'].data.iframeSrcEx;
  1333. }
  1334.  
  1335. // remove adblock detector parameters and clean up detector cookie
  1336. if ('adb' in x) {
  1337. let cookie = x.adb.data ? x.adb.data.cookie : undefined;
  1338. if (cookie) {
  1339. selectiveCookies(cookie);
  1340. x.adb.data.adb = 0;
  1341. }
  1342. delete x.adb;
  1343. }
  1344.  
  1345. return x;
  1346. };
  1347. // Yandex banner on main page and some other things
  1348. let _home = win.home,
  1349. _home_set = !!_home;
  1350. Object.defineProperty(win, 'home', {
  1351. get: () => _home,
  1352. set: vl => {
  1353. if (!_home_set && vl === _home)
  1354. return;
  1355. _home_set = false;
  1356. _console.log('home = %o', vl);
  1357. let _home_export = parseExport(vl.export);
  1358. Object.defineProperty(vl, 'export', {
  1359. get: () => _home_export,
  1360. set: vl => {
  1361. _home_export = parseExport(vl);
  1362. }
  1363. });
  1364. _home = vl;
  1365. }
  1366. });
  1367. // adblock circumvention on some Yandex domains
  1368. yandexRavenStub();
  1369. // yandex.ru/news/ and yandex.ru/sport/
  1370. abortExecution(onAccess.Get, 'yaads.adRenderedCount');
  1371. nt.define('Object.prototype.AdvertPartner', nt.func(false));
  1372. // ads in videoplayer
  1373. if (location.pathname.startsWith('/embed/')) {
  1374. let _Sandbox = undefined;
  1375. const _apply = Reflect.apply,
  1376. _define = Object.defineProperty;
  1377. _define(win, 'Sandbox', {
  1378. get: () => _Sandbox,
  1379. set: vl => {
  1380. if (vl && vl !== _Sandbox) {
  1381. let _decl = vl.decl,
  1382. _init = vl.init;
  1383. _define(vl, 'init', {
  1384. get: () => _init,
  1385. set: vi => {
  1386. _init = new Proxy(vi, {
  1387. apply (fun, that, args) {
  1388. let cfg = args[0];
  1389. if ('ad_config_json' in cfg)
  1390. cfg.ad_config_json = '{}';
  1391. if ('ad_genre_json' in cfg)
  1392. cfg.ad_config_json = '[]';
  1393. if ('ad_genre_json_hash' in cfg)
  1394. cfg.ad_genre_json_hash = '{ad_genre_json_hash}';
  1395. if ('with_ad_insertion' in cfg)
  1396. cfg.with_ad_insertion = 'false';
  1397. if ('tracking_events' in cfg)
  1398. cfg.tracking_events = {};
  1399. return _apply(fun, that, args);
  1400. }
  1401. });
  1402. }
  1403. });
  1404. _define(vl, 'decl', {
  1405. get: () => _decl,
  1406. set: vd => {
  1407. _decl = new Proxy(vd, {
  1408. apply (fun, that, args) {
  1409. let cfg = args[0];
  1410. if ('_getAdConfig' in cfg)
  1411. cfg._getAdConfig = new Proxy(cfg._getAdConfig, {
  1412. apply (fun, that, args) {
  1413. let res = _apply(fun, that, args);
  1414. if (res.hasPreroll)
  1415. res.hasPreroll = false;
  1416. return res;
  1417. }
  1418. });
  1419. return _apply(fun, that, args);
  1420. }
  1421. });
  1422. }
  1423. });
  1424. }
  1425. _Sandbox = vl;
  1426. }
  1427. });
  1428. }
  1429. // abp detector cookie on yandex pogoda and afisha
  1430. const _apply = Reflect.apply
  1431. win.Element.prototype.getAttribute = new Proxy(win.Element.prototype.getAttribute, {
  1432. apply (get, el, args) {
  1433. let res = _apply(get, el, args);
  1434. if (res && res.length > 20 && el instanceof HTMLBodyElement)
  1435. try {
  1436. let o = JSON.parse(res),
  1437. found = false, check;
  1438. for (let prop in o) {
  1439. check = 'param' in o[prop] || 'aabCookieName' in o[prop];
  1440. if (check || 'banners' in o[prop]) {
  1441. found = true;
  1442. if (check)
  1443. selectiveCookies(o[prop].param || o[prop].aabCookieName);
  1444. _console.log('%s %o removed %o', el.tagName, o, o[prop]);
  1445. delete o[prop];
  1446. }
  1447. }
  1448. if (!found) _console.log('%s %o', el.tagName, o);
  1449. res = JSON.stringify(o);
  1450. } catch(ignore) {}
  1451. return res;
  1452. }
  1453. });
  1454. }, nullTools, yandexRavenStub, 'let _setAttribute = Function.prototype.call.bind(_Element.setAttribute)',
  1455. abortExecutionModule, selectiveCookies, selectiveEval);
  1456.  
  1457. if ('attachShadow' in _Element) {
  1458. let fakeRoot = () => ({
  1459. firstChild: null,
  1460. appendChild: () => null,
  1461. querySelector: () => null,
  1462. querySelectorAll: () => null
  1463. });
  1464. _Element.createShadowRoot = fakeRoot;
  1465. let shadows = new WeakMap();
  1466. let _attachShadow = Object.getOwnPropertyDescriptor(_Element, 'attachShadow');
  1467. _attachShadow.value = function() {
  1468. return shadows.set(this, fakeRoot()).get(this);
  1469. };
  1470. Object.defineProperty(_Element, 'attachShadow', _attachShadow);
  1471. let _shadowRoot = Object.getOwnPropertyDescriptor(_Element, 'shadowRoot');
  1472. _shadowRoot.set = () => null;
  1473. _shadowRoot.get = function() {
  1474. return shadows.has(this) ? shadows.get(this) : undefined;
  1475. };
  1476. Object.defineProperty(_Element, 'shadowRoot', _shadowRoot);
  1477. }
  1478.  
  1479. // Disable banner styleSheet (on main page)
  1480. document.addEventListener('DOMContentLoaded', () => {
  1481. for (let sheet of document.styleSheets)
  1482. try {
  1483. for (let rule of sheet.cssRules)
  1484. if (rule.cssText.includes(' 728px 90px')) {
  1485. rule.parentStyleSheet.disabled = true;
  1486. _console.log('Disabled banner styleSheet: %o', rule.parentStyleSheet);
  1487. }
  1488. } catch(ignore) {}
  1489. }, false);
  1490.  
  1491. // Partially based on https://greasyfork.org/en/scripts/22737-remove-yandex-redirect
  1492. let selectors = (
  1493. 'A[onmousedown*="/jsredir"],'+
  1494. 'A[data-vdir-href],'+
  1495. 'A[data-counter]'
  1496. );
  1497. let removeTrackingAttributes = function(link) {
  1498. link.removeAttribute('onmousedown');
  1499. if (link.hasAttribute('data-vdir-href')) {
  1500. link.removeAttribute('data-vdir-href');
  1501. link.removeAttribute('data-orig-href');
  1502. }
  1503. if (link.hasAttribute('data-counter')) {
  1504. link.removeAttribute('data-counter');
  1505. link.removeAttribute('data-bem');
  1506. }
  1507. };
  1508. let removeTracking = function(scope) {
  1509. if (scope instanceof Element)
  1510. for (let link of scope.querySelectorAll(selectors))
  1511. removeTrackingAttributes(link);
  1512. };
  1513. _document.addEventListener('DOMContentLoaded', (e) => removeTracking(e.target));
  1514. (new MutationObserver(
  1515. function(ms) {
  1516. let m, node;
  1517. for (m of ms) for (node of m.addedNodes)
  1518. if (node instanceof HTMLAnchorElement && node.matches(selectors))
  1519. removeTrackingAttributes(node);
  1520. else
  1521. removeTracking(node);
  1522. }
  1523. )).observe(_de, { childList: true, subtree: true });
  1524. }
  1525.  
  1526. // Based on https://greasyfork.org/en/scripts/21937-moonwalk-hdgo-kodik-fix v0.8
  1527. PlayerFix: {
  1528. let log = name => _console.log(`Player FIX: Detected ${name} player in ${location.href}`);
  1529. function removeVast (data) {
  1530. if (data && typeof data === 'object') {
  1531. _console.log('Player configuration: %o', data);
  1532. if (data.advert_script && data.advert_script !== '') {
  1533. _console.log('Set data.advert_script to empty string.');
  1534. data.advert_script = '';
  1535. }
  1536. let keys = Object.getOwnPropertyNames(data);
  1537. let isVast = name => /vast|clickunder/.test(name);
  1538. if (!keys.some(isVast))
  1539. return data;
  1540. for (let key of keys)
  1541. if (typeof data[key] === 'object' && key !== 'links') {
  1542. _console.log(`Removed data.${key} %o`, data[key]);
  1543. delete data[key];
  1544. }
  1545. if (data.chain) {
  1546. let need = [],
  1547. drop = [],
  1548. links = data.chain.split('.');
  1549. for (let link of links)
  1550. if (!isVast(link))
  1551. need.push(link);
  1552. else
  1553. drop.push(link);
  1554. _console.log('Dropped from the chain:', ...drop);
  1555. data.chain = need.join('.');
  1556. }
  1557. }
  1558. return data;
  1559. }
  1560.  
  1561. let _hasOwnProperty = win.Function.prototype.apply.bind(win.Object.prototype.hasOwnProperty);
  1562. let _construct = win.Reflect.construct;
  1563. _document.addEventListener(
  1564. 'DOMContentLoaded', function() {
  1565. if ('video_balancer_options' in win && 'event_callback' in win) {
  1566. log('Moonwalk');
  1567. if (video_balancer_options.adv)
  1568. removeVast(video_balancer_options.adv);
  1569. if ('_mw_adb' in win)
  1570. Object.defineProperty(win, '_mw_adb', {
  1571. get: () => false,
  1572. set: () => true
  1573. });
  1574. } else if (win.startKodikPlayer !== undefined) {
  1575. log('Kodik');
  1576. // skip attempt to block access to HD resolutions
  1577. let chainCall = new Proxy({}, { get: () => () => chainCall });
  1578. if ($ && $.prototype && $.prototype.addClass) {
  1579. let $addClass = $.prototype.addClass;
  1580. $.prototype.addClass = function (className) {
  1581. if (className === 'blocked')
  1582. return chainCall;
  1583. return $addClass.apply(this, arguments);
  1584. };
  1585. }
  1586. // remove ad links from the metadata
  1587. let _ajax = win.$.ajax;
  1588. win.$.ajax = (params, ...args) => {
  1589. if (params.success) {
  1590. let _s = params.success;
  1591. params.success = (data, ...args) => _s(removeVast(data), ...args);
  1592. }
  1593. return _ajax(params, ...args);
  1594. }
  1595. } else if (win.getnextepisode && win.uppodEvent) {
  1596. log('Share-Serials.net');
  1597. scriptLander(
  1598. function() {
  1599. let _setInterval = win.setInterval,
  1600. _setTimeout = win.setTimeout,
  1601. _toString = Function.prototype.call.bind(Function.prototype.toString);
  1602. win.setInterval = function(func) {
  1603. if (func instanceof Function && _toString(func).includes('_delay')) {
  1604. let intv = _setInterval.call(
  1605. this, function() {
  1606. _setTimeout.call(
  1607. this, function(intv) {
  1608. clearInterval(intv);
  1609. let timer = _document.querySelector('#timer');
  1610. if (timer)
  1611. timer.click();
  1612. }, 100, intv);
  1613. func.call(this);
  1614. }, 5
  1615. );
  1616.  
  1617. return intv;
  1618. }
  1619. return _setInterval.apply(this, arguments);
  1620. };
  1621. win.setTimeout = function(func) {
  1622. if (func instanceof Function && _toString(func).includes('adv_showed'))
  1623. return _setTimeout.call(this, func, 0);
  1624. return _setTimeout.apply(this, arguments);
  1625. };
  1626. }
  1627. );
  1628. } else if ('ADC' in win) {
  1629. log('vjs-creatives plugin in');
  1630. let replacer = (obj) => {
  1631. for (let name in obj)
  1632. if (obj[name] instanceof Function)
  1633. obj[name] = () => null;
  1634. };
  1635. replacer(win.ADC);
  1636. replacer(win.currentAdSlot);
  1637. } else if ('Playerjs' in win) {
  1638. log('Playerjs');
  1639. win.Playerjs = new Proxy(win.Playerjs, {
  1640. construct (fn, args) {
  1641. let params = args[0];
  1642. if (params && typeof params === 'object') {
  1643. delete params.preroll;
  1644. params = removeVast(params);
  1645. Object.defineProperty(params, 'hasOwnProperty', {
  1646. value: function(...args) {
  1647. let res = _hasOwnProperty(this, args);
  1648. if (typeof args[0] === 'string' && args[0].startsWith('vast_') &&
  1649. res && params[args[0]]) {
  1650. _console.log(`Removed params.${args[0]} %o`, params[args[0]]);
  1651. delete params[args[0]];
  1652. return false;
  1653. }
  1654. return res;
  1655. },
  1656. enumerable: false,
  1657. configurable: true
  1658. });
  1659. }
  1660. return _construct(fn, args);
  1661. }
  1662. });
  1663. }
  1664.  
  1665. UberVK: {
  1666. if (!inIFrame)
  1667. break UberVK;
  1668. let oddNames = 'HD' in win &&
  1669. !Object.getOwnPropertyNames(win).every(n => !n.startsWith('_0x'));
  1670. if (!oddNames)
  1671. break UberVK;
  1672. log('UberVK');
  1673. XMLHttpRequest.prototype.open = () => {
  1674. throw 404;
  1675. };
  1676. }
  1677. }, false
  1678. );
  1679. }
  1680.  
  1681. // Applies wrapper function on the current page and all newly created same-origin iframes
  1682. // This is used to prevent trick which allows to get fresh page API through newly created same-origin iframes
  1683. function deepWrapAPI(wrapper) {
  1684. let wrapped = new WeakSet();
  1685. const log = (...args) => false && _console.log(...args),
  1686. bindApply = fun => Function.prototype.apply.bind(fun),
  1687. _apply = Reflect.apply;
  1688. const _HTMLIFrameElement = HTMLIFrameElement.prototype,
  1689. isIFrameElement = _HTMLIFrameElement.isPrototypeOf.bind(_HTMLIFrameElement);
  1690. const _contentWindow = Object.getOwnPropertyDescriptor(_HTMLIFrameElement, 'contentWindow'),
  1691. _get_contentWindow = bindApply(_contentWindow.get);
  1692.  
  1693. function wrapAPI(root) {
  1694. if (!root || wrapped.has(root))
  1695. return;
  1696. wrapped.add(root);
  1697. try {
  1698. wrapper(isIFrameElement(root) ? _get_contentWindow(root) : root);
  1699. log('Wrapped API in', (root === win) ? "main window." : root);
  1700. } catch(e) {
  1701. log('Failed to wrap API in', (root === win) ? "main window." : root, '\n', e);
  1702. }
  1703. };
  1704.  
  1705. // wrap API on contentWindow access
  1706. const getter = { apply (get, that, args) {
  1707. wrapAPI(that);
  1708. return _apply(get, that, args);
  1709. }};
  1710. _contentWindow.get = new Proxy(_contentWindow.get, getter);
  1711. Object.defineProperty(_HTMLIFrameElement, 'contentWindow', _contentWindow);
  1712. // wrap API on contentDocument access
  1713. const _contentDocument = Object.getOwnPropertyDescriptor(_HTMLIFrameElement, 'contentDocument');
  1714. _contentDocument.get = new Proxy(_contentDocument.get, getter);
  1715. Object.defineProperty(_HTMLIFrameElement, 'contentDocument', _contentDocument);
  1716.  
  1717. // manual children objects traverser to avoid issues
  1718. // with calling querySelectorAll on wrong types of objects
  1719. const _nodeType = bindApply(Object.getOwnPropertyDescriptor(_Node, 'nodeType').get),
  1720. _childNodes = bindApply(Object.getOwnPropertyDescriptor(_Node, 'childNodes').get),
  1721. _ELEMENT_NODE = _Node.ELEMENT_NODE,
  1722. _DOCUMENT_FRAGMENT_NODE = _Node.DOCUMENT_FRAGMENT_NODE
  1723. const wrapFrames = root => {
  1724. if (_nodeType(root) !== _ELEMENT_NODE && _nodeType(root) !== _DOCUMENT_FRAGMENT_NODE)
  1725. return; // only process nodes which may contain an IFRAME or be one
  1726. if (isIFrameElement(root)) {
  1727. wrapAPI(root);
  1728. return;
  1729. }
  1730. for (let child of _childNodes(root))
  1731. wrapFrames(child);
  1732. };
  1733.  
  1734. // wrap API in a newly appended iframe objects
  1735. _Node.appendChild = new Proxy(_Node.appendChild, {
  1736. apply (fun, that, args) {
  1737. let res = _apply(fun, that, args);
  1738. wrapFrames(args[0]);
  1739. return res;
  1740. }
  1741. });
  1742.  
  1743. // wrap API in iframe objects created with innerHTML of element on page
  1744. const _innerHTML = Object.getOwnPropertyDescriptor(_Element, 'innerHTML');
  1745. _innerHTML.set = new Proxy(_innerHTML.set, {
  1746. apply (set, that, args) {
  1747. _apply(set, that, args);
  1748. if (_document.contains(that))
  1749. wrapFrames(that);
  1750. }
  1751. });
  1752. Object.defineProperty(_Element, 'innerHTML', _innerHTML);
  1753.  
  1754. wrapAPI(win);
  1755. }
  1756.  
  1757. // piguiqproxy.com / zmctrack.net circumvention and onerror callback prevention
  1758. scriptLander(
  1759. () => {
  1760. // onerror callback blacklist
  1761. let masks = [],
  1762. //blockAll = /(^|\.)(rutracker-org\.appspot\.com)$/,
  1763. isBlocked = url => masks.some(mask => mask.test(url));// || blockAll.test(location.hostname);
  1764. for (let filter of [// blacklist
  1765. // global
  1766. '/adv/www/',
  1767. // adservers
  1768. '||185.87.50.147^',
  1769. '||10root25.website^', '||24video.xxx^',
  1770. '||adlabs.ru^', '||adspayformymortgage.win^', '||amgload.net^', '||aviabay.ru^',
  1771. '||bgrndi.com^', '||brokeloy.com^',
  1772. '||cdnjs-aws.ru^','||cnamerutor.ru^',
  1773. '||directadvert.ru^', '||docfilms.info^', '||dreadfula.ru^', '||dsn-fishki.ru^',
  1774. '||et-cod.com^', '||et-code.ru^', '||etcodes.com^',
  1775. /*'||franecki.net^',*/ '||film-doma.ru^',
  1776. '||free-torrent.org^', '||free-torrent.pw^',
  1777. '||free-torrents.org^', '||free-torrents.pw^',
  1778. '||game-torrent.info^', '||gocdn.ru^',
  1779. '||hdkinoshka.com^', '||hghit.com^', '||hindcine.net^',
  1780. '||kinotochka.net^', '||kinott.com^', '||kinott.ru^',
  1781. '||klcheck.com^', '||kuveres.com^',
  1782. '||lepubs.com^', '||luxadv.com^', '||luxup.ru^', '||luxupcdna.com^',
  1783. '||marketgid.com^', '||mebablo.com^', '||mixadvert.com^', '||mxtads.com^',
  1784. '||nickhel.com^',
  1785. '||oconner.biz^', '||oconner.link^', '||octoclick.net^', '||octozoon.org^',
  1786. '||pigiuqproxy.com^', '||piguiqproxy.com^', '||pkpojhc.com^',
  1787. '||psma01.com^', '||psma02.com^', '||psma03.com^',
  1788. '||rcdn.pro^', '||recreativ.ru^', '||redtram.com^', '||regpole.com^',
  1789. '||rootmedia.ws^', '||ruttwind.com^', '||rutvind.com^',
  1790. '||skidl.ru^', '||smi2.net^', '||smcheck.org^',
  1791. '||torvind.com^', '||traffic-media.co^', '||trafmag.com^', '||trustjs.net^', '||ttarget.ru^',
  1792. '||u-dot-id-adtool.appspot.com^', '||utarget.ru^',
  1793. '||webadvert-gid.ru^', '||webadvertgid.ru^',
  1794. '||xxuhter.ru^',
  1795. '||yuiout.online^',
  1796. '||zmctrack.net^', '||zoom-film.ru^'])
  1797. masks.push(new RegExp(
  1798. filter.replace(/([\\/[\].+?(){}$])/g, '\\$1')
  1799. .replace(/\*/g, '.*?')
  1800. .replace(/\^(?!$)/g,'\\.?[^\\w%._-]')
  1801. .replace(/\^$/,'\\.?([^\\w%._-]|$)')
  1802. .replace(/^\|\|/,'^(ws|http)s?:\\/+([^/.]+\\.)*?'),
  1803. 'i'));
  1804. // main script
  1805. deepWrapAPI(root => {
  1806. let _call = root.Function.prototype.call,
  1807. _defineProperty = root.Object.defineProperty,
  1808. _getOwnPropertyDescriptor = root.Object.getOwnPropertyDescriptor;
  1809. onerror: {
  1810. // 'onerror' handler for scripts from blacklisted sources
  1811. let scriptMap = new WeakMap();
  1812. const _apply = root.Reflect.apply,
  1813. _HTMLScriptElement = root.HTMLScriptElement,
  1814. _HTMLImageElement = root.HTMLImageElement;
  1815. const _get_tagName = _call.bind(_getOwnPropertyDescriptor(root.Element.prototype, 'tagName').get),
  1816. _get_scr_src = _call.bind(_getOwnPropertyDescriptor(_HTMLScriptElement.prototype, 'src').get),
  1817. _get_img_src = _call.bind(_getOwnPropertyDescriptor(_HTMLImageElement.prototype, 'src').get);
  1818. const _get_src = node => {
  1819. if (node instanceof _HTMLScriptElement)
  1820. return _get_scr_src(node);
  1821. if (node instanceof _HTMLImageElement)
  1822. return _get_img_src(node);
  1823. return undefined
  1824. };
  1825. const _onerror = _getOwnPropertyDescriptor(root.HTMLElement.prototype, 'onerror'),
  1826. _set_onerror = _call.bind(_onerror.set);
  1827. _onerror.get = function() {
  1828. return scriptMap.get(this) || null;
  1829. };
  1830. _onerror.set = function(callback) {
  1831. if (typeof callback !== 'function') {
  1832. scriptMap.delete(this);
  1833. _set_onerror(this, callback);
  1834. return;
  1835. }
  1836. scriptMap.set(this, callback);
  1837. _set_onerror(this, function() {
  1838. let src = _get_src(this);
  1839. if (isBlocked(src)) {
  1840. _console.trace(`Blocked "onerror" callback from ${_get_tagName(this)}: ${src}`);
  1841. return;
  1842. }
  1843. _apply(scriptMap.get(this), this, arguments);
  1844. });
  1845. };
  1846. _defineProperty(root.HTMLElement.prototype, 'onerror', _onerror);
  1847. }
  1848. // Simplistic WebSocket wrapper for Maxthon and Firefox before v58
  1849. WSWrap: { // once again seems required in Google Chrome and similar browsers due to zmctrack.net -_-
  1850. if (true /*/Maxthon/.test(navigator.appVersion) ||
  1851. 'InstallTrigger' in win && 'StopIteration' in win*/) {
  1852. let _ws = _getOwnPropertyDescriptor(root, 'WebSocket');
  1853. if (!_ws)
  1854. break WSWrap;
  1855. _ws.value = new Proxy(_ws.value, {
  1856. construct: (ws, args) => {
  1857. if (isBlocked(args[0])) {
  1858. _console.log('Blocked WS connection:', args[0]);
  1859. return {};
  1860. }
  1861. return new ws(...args);
  1862. }
  1863. });
  1864. _defineProperty(root, 'WebSocket', _ws);
  1865. }
  1866. }
  1867. untrustedClick: {
  1868. // Block popular method to open a new window in Google Chrome by dispatching a custom click
  1869. // event on a newly created anchor with _blank target. Untrusted events must not open new windows.
  1870. let _dispatchEvent = _call.bind(root.EventTarget.prototype.dispatchEvent);
  1871. root.EventTarget.prototype.dispatchEvent = function dispatchEvent(e) {
  1872. if (!e.isTrusted && e.type === 'click' && e.constructor.name === 'MouseEvent' &&
  1873. !this.parentNode && this.tagName === 'A' && this.target[0] === '_') {
  1874. _console.log('Blocked dispatching a click event on a parentless anchor: %o', this);
  1875. return;
  1876. }
  1877. return _dispatchEvent(this, ...arguments);
  1878. };
  1879. }
  1880. // XHR Wrapper
  1881. let _proto = undefined;
  1882. try {
  1883. _proto = root.XMLHttpRequest.prototype;
  1884. } catch(ignore) {
  1885. return;
  1886. };
  1887. // blacklist of domains where all third-party requests are ignored
  1888. const ondomains = /(^|[/.@])oane\.ws($|[:/])/i;
  1889. // highly suspicious URLs
  1890. const suspicious = /^(https?:)?\/\/(?!(rutube|shazoo|worldoftanks)\.ru[:/])(csp-)?([a-z0-9]{6}){1,2}\.ru\//i;
  1891. const on_get_ban = /^(https?:)?\/\/(?!(rutube|shazoo|worldoftanks)\.ru[:/])(csp-)?([a-z0-9]{6}){1,2}\.ru\/([a-z0-9/]{40,}|[a-z0-9]{8,}|ad\/banner\/.+|show\/\?\d+=\d+&.+)$/i;
  1892. const on_post_ban = /^(https?:)?\/\/(?!(rutube|shazoo|worldoftanks)\.ru[:/])(csp-)?([a-z0-9]{6}){1,2}\.ru\/([a-z0-9]{6,})$/i;
  1893. const yandex_direct = /^(https?:)?\/\/([^.]+\.)??yandex(\.[a-z]{2,3}){1,2}\/((images|weather)\/[a-z0-9/_-]{40,}|jstracer?|j?clck\/.*|set\/s\/rsya-tag-users\/data(\?.*)?|static\/main\.js(\?.*)?)$/i;
  1894. const more_y_direct = /^(https?:)?\/\/((([^.]+\.)??(24smi\.org|(echo\.msk|drive2|kakprosto|liveinternet|razlozhi)\.ru)\/(.{290,}|[a-z0-9/_-]{100,}))|yastatic\.net\/.*?\/chunks\/promo\/.*)$/i;
  1895. const whitelist = /^(https?:)?\/\/yandex\.ru\/yobject$/;
  1896. const fabPatterns = /\/fuckadblock/i;
  1897.  
  1898. const blockedUrls = new Set();
  1899. function checkRequest(fname, method, url) {
  1900. let block = isBlocked(url) ||
  1901. ondomains.test(location.hostname) && !ondomains.test(url) ||
  1902. method !== 'POST' && on_get_ban.test(url) ||
  1903. method === 'POST' && on_post_ban.test(url) ||
  1904. yandex_direct.test(url) || more_y_direct.test(url);
  1905. let allow = block && whitelist.test(url) ||
  1906. // Fix for infinite load on Yandex Images: find image, open "other sizes and similar images" in a new tab, click on a preview of a similar image
  1907. (block && method === 'script.src' &&
  1908. root.location.pathname === '/images/search' && root.location.hostname.startsWith('yandex.') &&
  1909. url.startsWith('http') && url.includes('/images/')) || // Direct URLs are similar, but don't have protocol for some reason
  1910. (block && root.location.hostname === 'widgets.kinopoisk.ru' && url.includes('/static/main.js?')) ||
  1911. (block && !url.startsWith('http') && // drive2.ru hid a little CSS style in their requests which shows page content like this
  1912. (root.location.hostname === 'drive2.ru' || root.location.hostname.endsWith('.drive2.ru')));
  1913. if (allow) {
  1914. block = false;
  1915. _console.trace(`Allowed ${fname} ${method} request %o from %o`, url, root.location.href);
  1916. }
  1917. if (block) {
  1918. if (!blockedUrls.has(url)) // don't repeat log if the same URL were blocked more than once
  1919. _console.trace(`Blocked ${fname} ${method} request %o from %o`, url, root.location.href);
  1920. blockedUrls.add(url);
  1921. return true;
  1922. }
  1923. if (!allow && suspicious.test(url))
  1924. _console.trace(`Suspicious ${fname} ${method} request %o from %o`, url, root.location.href);
  1925. return false;
  1926. }
  1927.  
  1928. // workaround for a broken weather mini-map on Yandex
  1929. let skip_xhr_check = false;
  1930. if (root.location.hostname.startsWith('yandex.') &&
  1931. root.location.pathname.startsWith('/pogoda/') ||
  1932. root.location.hostname.endsWith('.kakprosto.ru'))
  1933. skip_xhr_check = true;
  1934.  
  1935. let xhrStopList = new WeakSet();
  1936. let _open = root.Function.prototype.apply.bind(_proto.open);
  1937. _proto.open = function open() {
  1938. '[native code]';
  1939. return !skip_xhr_check && checkRequest('xhr', ...arguments) ?
  1940. (xhrStopList.add(this), undefined) : _open(this, arguments);
  1941. };
  1942. ['send', 'setRequestHeader', 'getAllResponseHeaders'].forEach(
  1943. name => {
  1944. let func = _proto[name];
  1945. _proto[name] = function(...args) {
  1946. return xhrStopList.has(this) ? null : func.apply(this, args);
  1947. };
  1948. }
  1949. );
  1950. // simulate readyState === 1 for blocked requests
  1951. let _readyState = Object.getOwnPropertyDescriptor(_proto, 'readyState');
  1952. let _get_readyState = root.Function.prototype.apply.bind(_readyState.get);
  1953. _readyState.get = function() {
  1954. return xhrStopList.has(this) ? 1 : _get_readyState(this, arguments);
  1955. }
  1956. Object.defineProperty(_proto, 'readyState', _readyState);
  1957.  
  1958. let _fetch = root.Function.prototype.apply.bind(root.fetch);
  1959. root.fetch = function fetch() {
  1960. '[native code]';
  1961. let url = arguments[0];
  1962. let method = arguments[1] ? arguments[1].method : undefined;
  1963. if (arguments[0] instanceof Request) {
  1964. method = url.method;
  1965. url = url.url;
  1966. }
  1967. if (checkRequest('fetch', method, url))
  1968. return new Promise(() => null);
  1969. return _fetch(root, arguments);
  1970. };
  1971.  
  1972. let _script_src = Object.getOwnPropertyDescriptor(root.HTMLScriptElement.prototype, 'src');
  1973. let _script_src_set = root.Function.prototype.apply.bind(_script_src.set);
  1974. let _dispatchEvent = root.Function.prototype.call.bind(root.EventTarget.prototype.dispatchEvent);
  1975. _script_src.set = function(src) {
  1976. if (fabPatterns.test(src)) {
  1977. _console.trace('Blocked set script.src request: %o', src);
  1978. deployFABStub(root);
  1979. setTimeout(() => {
  1980. let e = root.document.createEvent('Event');
  1981. e.initEvent('load', false, false);
  1982. _dispatchEvent(this, e);
  1983. }, 0);
  1984. return;
  1985. }
  1986. return checkRequest('set', 'script.src', src) || _script_src_set(this, arguments);
  1987. };
  1988. Object.defineProperty(root.HTMLScriptElement.prototype, 'src', _script_src);
  1989.  
  1990. let adregain_pattern = /ggg==" alt="advertisement"/;
  1991. if (root.self !== root.top) { // in IFrame
  1992. let _write = Function.prototype.call.bind(root.document.write);
  1993. root.document.write = function write(text, ...args) {
  1994. "[native code]";
  1995. if (adregain_pattern.test(text)) {
  1996. _console.log('Skipped AdRegain frame.');
  1997. return _write(this, '');
  1998. }
  1999. return _write(this, text, ...args);
  2000. };
  2001. }
  2002. });
  2003. }, deepWrapAPI
  2004. );
  2005.  
  2006. // === Helper functions ===
  2007.  
  2008. // function to search and remove nodes by content
  2009. // selector - standard CSS selector to define set of nodes to check
  2010. // words - regular expression to check content of the suspicious nodes
  2011. // params - object with multiple extra parameters:
  2012. // .log - display log in the console
  2013. // .hide - set display to none instead of removing from the page
  2014. // .parent - parent node to remove if content is found in the child node
  2015. // .siblings - number of simling nodes to remove (excluding text nodes)
  2016. let scRemove = (node) => node.parentNode.removeChild(node);
  2017. let scHide = function(node) {
  2018. let style = _getAttribute(node, 'style') || '',
  2019. hide = ';display:none!important;';
  2020. if (style.indexOf(hide) < 0)
  2021. _setAttribute(node, 'style', style + hide);
  2022. };
  2023.  
  2024. function scissors (selector, words, scope, params) {
  2025. let logger = (...args) => { if (params.log) _console.log(...args) };
  2026. if (!scope.contains(_document.body))
  2027. logger('[s] scope', scope);
  2028. let remFunc = (params.hide ? scHide : scRemove),
  2029. iterFunc = (params.siblings > 0 ? 'nextElementSibling' : 'previousElementSibling'),
  2030. toRemove = [],
  2031. siblings;
  2032. for (let node of scope.querySelectorAll(selector)) {
  2033. // drill up to a parent node if specified, break if not found
  2034. if (params.parent) {
  2035. let old = node;
  2036. node = node.closest(params.parent);
  2037. if (node === null || node.contains(scope)) {
  2038. logger('[s] went out of scope with', old);
  2039. continue;
  2040. }
  2041. }
  2042. logger('[s] processing', node);
  2043. if (toRemove.includes(node))
  2044. continue;
  2045. if (words.test(node.innerHTML)) {
  2046. // skip node if already marked for removal
  2047. logger('[s] marked for removal');
  2048. toRemove.push(node);
  2049. // add multiple nodes if defined more than one sibling
  2050. siblings = Math.abs(params.siblings) || 0;
  2051. while (siblings) {
  2052. node = node[iterFunc];
  2053. if (!node) break; // can't go any further - exit
  2054. logger('[s] adding sibling node', node);
  2055. toRemove.push(node);
  2056. siblings -= 1;
  2057. }
  2058. }
  2059. }
  2060. let toSkip = [];
  2061. for (let node of toRemove)
  2062. if (!toRemove.every(other => other === node || !node.contains(other)))
  2063. toSkip.push(node);
  2064. if (toRemove.length)
  2065. logger(`[s] proceeding with ${params.hide?'hide':'removal'} of`, toRemove, `skip`, toSkip);
  2066. for (let node of toRemove) if (!toSkip.includes(node))
  2067. remFunc(node);
  2068. }
  2069.  
  2070. // function to perform multiple checks if ads inserted with a delay
  2071. // by default does 30 checks withing a 3 seconds unless nonstop mode specified
  2072. // also does 1 extra check when a page completely loads
  2073. // selector and words - passed dow to scissors
  2074. // params - object with multiple extra parameters:
  2075. // .log - display log in the console
  2076. // .root - selector to narrow down scope to scan;
  2077. // .observe - if true then check will be performed continuously;
  2078. // Other parameters passed down to scissors.
  2079. function gardener(selector, words, params) {
  2080. let logger = (...args) => { if (params.log) _console.log(...args) };
  2081. params = params || {};
  2082. logger(`[gardener] selector: '${selector}' detector: ${words} options: ${JSON.stringify(params)}`);
  2083. let scope;
  2084. let globalScope = [_de];
  2085. let domLoaded = false;
  2086. let getScope = root => root ? _de.querySelectorAll(root) : globalScope;
  2087. let onevent = e => {
  2088. logger(`[gardener] cleanup on ${Object.getPrototypeOf(e)} "${e.type}"`);
  2089. for (let node of scope)
  2090. scissors(selector, words, node, params);
  2091. };
  2092. let repeater = n => {
  2093. if (!domLoaded && n) {
  2094. setTimeout(repeater, 500, n - 1);
  2095. scope = getScope(params.root);
  2096. if (!scope) // exit if the root element is not present on the page
  2097. return 0;
  2098. onevent({type: 'Repeater'});
  2099. }
  2100. };
  2101. repeater(20);
  2102. _document.addEventListener(
  2103. 'DOMContentLoaded', (e) => {
  2104. domLoaded = true;
  2105. // narrow down scope to a specific element
  2106. scope = getScope(params.root);
  2107. if (!scope) // exit if the root element is not present on the page
  2108. return 0;
  2109. logger('[g] scope', scope);
  2110. // add observe mode if required
  2111. if (params.observe) {
  2112. let params = { childList:true, subtree: true };
  2113. let observer = new MutationObserver(
  2114. function(ms) {
  2115. for (let m of ms)
  2116. if (m.addedNodes.length)
  2117. onevent(m);
  2118. }
  2119. );
  2120. for (let node of scope)
  2121. observer.observe(node, params);
  2122. logger('[g] observer enabled');
  2123. }
  2124. onevent(e);
  2125. }, false);
  2126. // wait for a full page load to do one extra cut
  2127. win.addEventListener('load', onevent, false);
  2128. }
  2129.  
  2130. // wrap popular methods to open a new tab to catch specific behaviours
  2131. function createWindowOpenWrapper(openFunc) {
  2132. let _createElement = _Document.createElement,
  2133. _appendChild = _Element.appendChild,
  2134. fakeNative = (f) => (f.toString = () => `function ${f.name}() { [native code] }`);
  2135.  
  2136. fakeNative(openFunc);
  2137.  
  2138. let parser = _createElement.call(_document, 'a');
  2139. let openWhitelist = (url, parent) => {
  2140. parser.href = url;
  2141. return parser.hostname === 'www.imdb.com' || parser.hostname === 'www.kinopoisk.ru' ||
  2142. parent.hostname === 'radikal.ru' && url === undefined;
  2143. };
  2144.  
  2145. let redefineOpen = (root) => {
  2146. if ('open' in root) {
  2147. let _open = root.open.bind(root);
  2148. nt.defineOn(root, 'open', (...args) => {
  2149. if (openWhitelist(args[0], location)) {
  2150. _console.log('Whitelisted popup:', ...args);
  2151. return _open(...args);
  2152. }
  2153. return openFunc(...args);
  2154. });
  2155. }
  2156. };
  2157. redefineOpen(win);
  2158.  
  2159. function createElement() {
  2160. '[native code]';
  2161. let el = _createElement.apply(this, arguments);
  2162. // redefine window.open in first-party frames
  2163. if (el instanceof HTMLIFrameElement || el instanceof HTMLObjectElement)
  2164. el.addEventListener('load', (e) => {
  2165. try {
  2166. redefineOpen(e.target.contentWindow);
  2167. } catch(ignore) {}
  2168. }, false);
  2169. return el;
  2170. }
  2171. fakeNative(createElement);
  2172.  
  2173. let redefineCreateElement = (obj) => {
  2174. for (let root of [obj.document, _Document]) if ('createElement' in root)
  2175. nt.defineOn(root, 'createElement', createElement, 'Document.prototype.');
  2176. };
  2177. redefineCreateElement(win);
  2178.  
  2179. // wrap window.open in newly added first-party frames
  2180. _Element.appendChild = function appendChild() {
  2181. '[native code]';
  2182. let el = _appendChild.apply(this, arguments);
  2183. if (el instanceof HTMLIFrameElement)
  2184. try {
  2185. redefineOpen(el.contentWindow);
  2186. redefineCreateElement(el.contentWindow);
  2187. } catch(ignore) {}
  2188. return el;
  2189. };
  2190. fakeNative(_Element.appendChild);
  2191. }
  2192.  
  2193. // Function to catch and block various methods to open a new window with 3rd-party content.
  2194. // Some advertisement networks went way past simple window.open call to circumvent default popup protection.
  2195. // This funciton blocks window.open, ability to restore original window.open from an IFRAME object,
  2196. // ability to perform an untrusted (not initiated by user) click on a link, click on a link without a parent
  2197. // node or simply a link with piece of javascript code in the HREF attribute.
  2198. function preventPopups() {
  2199. // call sandbox-me if in iframe and not whitelisted
  2200. if (inIFrame) {
  2201. win.top.postMessage({ name: 'sandbox-me', href: win.location.href }, '*');
  2202. return;
  2203. }
  2204.  
  2205. scriptLander(() => {
  2206. let open = (...args) => {
  2207. '[native code]';
  2208. _console.trace('Site attempted to open a new window', ...args);
  2209. return {
  2210. document: nt.proxy({
  2211. write: nt.func({}, 'write'),
  2212. writeln: nt.func({}, 'writeln')
  2213. }),
  2214. location: nt.proxy({})
  2215. };
  2216. };
  2217.  
  2218. createWindowOpenWrapper(open);
  2219.  
  2220. _console.log('Popup prevention enabled.');
  2221. }, nullTools, createWindowOpenWrapper);
  2222. }
  2223.  
  2224. // Helper function to close background tab if site opens itself in a new tab and then
  2225. // loads a 3rd-party page in the background one (thus performing background redirect).
  2226. function preventPopunders() {
  2227. // create "close_me" event to call high-level window.close()
  2228. let eventName = `close_me_${Math.random().toString(36).substr(2)}`;
  2229. let callClose = () => {
  2230. _console.log('close call');
  2231. window.close();
  2232. };
  2233. window.addEventListener(eventName, callClose, true);
  2234.  
  2235. scriptLander(() => {
  2236. // get host of a provided URL with help of an anchor object
  2237. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  2238. let parseURL = _document.createElement('A');
  2239. let getHost = url => {
  2240. parseURL.href = url;
  2241. return parseURL.hostname
  2242. };
  2243. // site went to a new tab and attempts to unload
  2244. // call for high-level close through event
  2245. let closeWindow = () => window.dispatchEvent(new CustomEvent(eventName, {}));
  2246. // check is URL local or goes to different site
  2247. let isLocal = (url) => {
  2248. if (url === location.pathname || url === location.href)
  2249. return true; // URL points to current pathname or full address
  2250. let host = getHost(url);
  2251. let site = location.hostname;
  2252. return host !== '' && // URLs with unusual protocol may have empty 'host'
  2253. (site === host || site.endsWith(`.${host}`) || host.endsWith(`.${site}`));
  2254. };
  2255.  
  2256. let _open = window.open.bind(window);
  2257. let open = (...args) => {
  2258. '[native code]';
  2259. let url = args[0];
  2260. if (url && isLocal(url))
  2261. window.addEventListener('beforeunload', closeWindow, true);
  2262. return _open(...args);
  2263. };
  2264.  
  2265. createWindowOpenWrapper(open);
  2266.  
  2267. _console.log("Background redirect prevention enabled.");
  2268. }, `let eventName="${eventName}"`, nullTools, createWindowOpenWrapper);
  2269. }
  2270.  
  2271. // Mix between check for popups and popunders
  2272. // Significantly more agressive than both and can't be used as universal solution
  2273. function preventPopMix() {
  2274. if (inIFrame) {
  2275. win.top.postMessage({ name: 'sandbox-me', href: win.location.href }, '*');
  2276. return;
  2277. }
  2278.  
  2279. // create "close_me" event to call high-level window.close()
  2280. let eventName = `close_me_${Math.random().toString(36).substr(2)}`;
  2281. let callClose = () => {
  2282. _console.log('close call');
  2283. window.close();
  2284. };
  2285. window.addEventListener(eventName, callClose, true);
  2286.  
  2287. scriptLander(() => {
  2288. let _open = window.open,
  2289. parseURL = _document.createElement('A');
  2290. // get host of a provided URL with help of an anchor object
  2291. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  2292. let getHost = (url) => {
  2293. parseURL.href = url;
  2294. return parseURL.host;
  2295. };
  2296. // site went to a new tab and attempts to unload
  2297. // call for high-level close through event
  2298. let closeWindow = () => {
  2299. _open(window.location,'_self');
  2300. window.dispatchEvent(new CustomEvent(eventName, {}));
  2301. };
  2302. // check is URL local or goes to different site
  2303. function isLocal(url) {
  2304. let loc = window.location;
  2305. if (url === loc.pathname || url === loc.href)
  2306. return true; // URL points to current pathname or full address
  2307. let host = getHost(url),
  2308. site = loc.host;
  2309. if (host === '')
  2310. return false; // URLs with unusual protocol may have empty 'host'
  2311. if (host.length > site.length)
  2312. [site, host] = [host, site];
  2313. return site.includes(host, site.length - host.length);
  2314. }
  2315.  
  2316. // add check for redirect for 5 seconds, then disable it
  2317. function checkRedirect() {
  2318. window.addEventListener('beforeunload', closeWindow, true);
  2319. setTimeout(closeWindow=>window.removeEventListener('beforeunload', closeWindow, true), 5000, closeWindow);
  2320. }
  2321.  
  2322. function open(url, name) {
  2323. '[native code]';
  2324. if (url && isLocal(url) && (!name || name === '_blank')) {
  2325. _console.trace('Suspicious local new window', ...arguments);
  2326. checkRedirect();
  2327. return _open.apply(this, arguments);
  2328. }
  2329. _console.trace('Blocked attempt to open a new window', ...arguments);
  2330. return {
  2331. document: {
  2332. write: () => {},
  2333. writeln: () => {}
  2334. }
  2335. };
  2336. }
  2337.  
  2338. function clickHandler(e) {
  2339. let link = e.target,
  2340. url = link.href||'';
  2341. if (e.targetParentNode && e.isTrusted || link.target !== '_blank') {
  2342. _console.log('Link', link, 'were created dinamically, but looks fine.');
  2343. return true;
  2344. }
  2345. if (isLocal(url) && link.target === '_blank') {
  2346. _console.log('Suspicious local link', link);
  2347. checkRedirect();
  2348. return;
  2349. }
  2350. _console.log('Blocked suspicious click on a link', link);
  2351. e.stopPropagation();
  2352. e.preventDefault();
  2353. }
  2354.  
  2355. createWindowOpenWrapper(open, clickHandler);
  2356.  
  2357. _console.log("Mixed popups prevention enabled.");
  2358. }, `let eventName="${eventName}"`, createWindowOpenWrapper);
  2359. }
  2360. // External listener for case when site known to open popups were loaded in iframe
  2361. // It will sandbox any iframe which will send message 'forbid.popups' (preventPopups sends it)
  2362. // Some sites replace frame's window.location with data-url to run in clean context
  2363. if (!inIFrame) window.addEventListener(
  2364. 'message', function(e) {
  2365. if (!e.data || e.data.name !== 'sandbox-me' || !e.data.href)
  2366. return;
  2367. let src = e.data.href;
  2368. for (let frame of _document.querySelectorAll('iframe'))
  2369. if (frame.contentWindow === e.source) {
  2370. if (frame.hasAttribute('sandbox')) {
  2371. if (!frame.sandbox.contains('allow-popups'))
  2372. return; // exit frame since it's already sandboxed and popups are blocked
  2373. // remove allow-popups if frame already sandboxed
  2374. frame.sandbox.remove('allow-popups');
  2375. } else
  2376. // set sandbox mode for troublesome frame and allow scripts, forms and a few other actions
  2377. // technically allowing both scripts and same-origin allows removal of the sandbox attribute,
  2378. // but to apply content must be reloaded and this script will re-apply it in the result
  2379. frame.setAttribute('sandbox','allow-forms allow-scripts allow-presentation allow-top-navigation allow-same-origin');
  2380. _console.log('Disallowed popups from iframe', frame);
  2381.  
  2382. // reload frame content to apply restrictions
  2383. if (!src) {
  2384. src = frame.src;
  2385. _console.log('Unable to get current iframe location, reloading from src', src);
  2386. } else
  2387. _console.log('Reloading iframe with URL', src);
  2388. frame.src = 'about:blank';
  2389. frame.src = src;
  2390. }
  2391. }, false
  2392. );
  2393.  
  2394. const evalPatternYandex = /{exports:{},id:r,loaded:!1}|containerId:(.|\r|\n)+params:/,
  2395. evalPatternGeneric = /_0x|location\s*?=|location.href\s*?=|location.assign\(|open\(/i;
  2396. function selectiveEval(...patterns) {
  2397. if (patterns.length === 0)
  2398. patterns.push(evalPatternGeneric);
  2399. let _eval_def = Object.getOwnPropertyDescriptor(win, 'eval');
  2400. if (!_eval_def || !_eval_def.value) {
  2401. _console.warn('Unable to wrap window.eval %o', _eval_def);
  2402. return;
  2403. }
  2404. let _eval_val = _eval_def.value;
  2405. _eval_def.value = function(...args) {
  2406. if (patterns.some(pattern => pattern.test(args[0]))) {
  2407. _console.trace(`Skipped eval of ${args[0].slice(0, 512)}\u2026`);
  2408. return null;
  2409. }
  2410. try {
  2411. return _eval_val.apply(this, args);
  2412. } catch(e) {
  2413. _console.error('Crash source:', args[0]);
  2414. throw e;
  2415. }
  2416. };
  2417. Object.defineProperty(win, 'eval', _eval_def);
  2418. }
  2419. selectiveEval.toString = new Proxy(selectiveEval.toString, {
  2420. apply: (...args) => Reflect.apply(...args) + `const evalPatternYandex = ${evalPatternYandex}, evalPatternGeneric = ${evalPatternGeneric}`
  2421. });
  2422.  
  2423. // hides cookies by pattern and attempts to remove them if they already set
  2424. // also prevents setting new versions of such cookies
  2425. function selectiveCookies(scPattern = '', scPaths = []) {
  2426. let patterns = scPattern.split('|');
  2427. if (patterns[0] !== ';default') {
  2428. // Google Analytics cookies
  2429. patterns.push('_g(at?|id)|__utm[a-z]');
  2430. // Yandex ABP detection cookies
  2431. patterns.push('bltsr|blcrm');
  2432. } else
  2433. patterns.shift();
  2434. let blacklist = new RegExp(`(^|;\\s?)(${patterns.join('|')})($|=)`);
  2435. if (isFirefox && scPaths.length)
  2436. scPaths = scPaths.concat(scPaths.map(path => `${path}/`));
  2437. scPaths.push('/');
  2438. let _doc_proto = ('cookie' in _Document) ? _Document : Object.getPrototypeOf(_document);
  2439. let _cookie = Object.getOwnPropertyDescriptor(_doc_proto, 'cookie');
  2440. if (_cookie) {
  2441. let _set_cookie = Function.prototype.call.bind(_cookie.set);
  2442. let _get_cookie = Function.prototype.call.bind(_cookie.get);
  2443. let expireDate = 'Thu, 01 Jan 1970 00:00:01 UTC';
  2444. let expireAge = '-99999999';
  2445. let expireBase = `=;expires=${expireDate};Max-Age=${expireAge}`;
  2446. let expireAttempted = {};
  2447. // expire is called from cookie getter and doesn't know exact parameters used to set cookies present there
  2448. // so, it will use path=/ by default if scPaths wasn't set and attempt to set cookies on all parent domains
  2449. let expire = (cookie, that) => {
  2450. let domain = that.location.hostname.split('.'),
  2451. name = cookie.replace(/=.*/,'');
  2452. scPaths.forEach(path =>_set_cookie(that, `${name}${expireBase};path=${path}`));
  2453. while (domain.length > 1) {
  2454. try {
  2455. scPaths.forEach(
  2456. path => _set_cookie(that, `${name}${expireBase};domain=${domain.join('.')};path=${path}`)
  2457. );
  2458. } catch(e) { _console.error(e); }
  2459. domain.shift();
  2460. }
  2461. expireAttempted[name] = true;
  2462. _console.log('Removing existing cookie:', cookie);
  2463. };
  2464. // skip setting unwanted cookies
  2465. _cookie.set = function(value) {
  2466. if (blacklist.test(value)) {
  2467. _console.trace('Ignored cookie: %s', value);
  2468. // try to remove same cookie if it already exists using exact values from the set string
  2469. if (blacklist.test(_get_cookie(this))) {
  2470. let parts = value.split(/;\s?/),
  2471. name = parts[0].replace(/=.*/,''),
  2472. newParts = [`${name}=`, `expires=${expireDate}`, `Max-Age=${expireAge}`],
  2473. skip = [name, 'expires', 'Max-Age'];
  2474. for (let part of parts)
  2475. if (!skip.includes(part.replace(/=.*/,'')))
  2476. newParts.push(part);
  2477. try {
  2478. _set_cookie(this, newParts.join(';'));
  2479. } catch(e) { _console.error(e); }
  2480. _console.log('Removing existing cookie:', name);
  2481. }
  2482. return;
  2483. }
  2484. return _set_cookie(this, value);
  2485. };
  2486. // hide unwanted cookies from site
  2487. _cookie.get = function() {
  2488. let res = _get_cookie(this);
  2489. if (blacklist.test(res)) {
  2490. let stack = [];
  2491. for (let cookie of res.split(/;\s?/))
  2492. if (!blacklist.test(cookie))
  2493. stack.push(cookie);
  2494. else {
  2495. let name = cookie.replace(/=.*/,'');
  2496. if (expireAttempted[name]) {
  2497. _console.log('Unable to expire:', cookie);
  2498. expireAttempted[name] = false;
  2499. }
  2500. if (!(name in expireAttempted))
  2501. expire(cookie, this);
  2502. }
  2503. res = stack.join('; ');
  2504. }
  2505. return res;
  2506. };
  2507. Object.defineProperty(_doc_proto, 'cookie', _cookie);
  2508. _console.log('Active cookies:', win.document.cookie);
  2509. }
  2510. }
  2511.  
  2512. // Locates a node with specific text in Russian
  2513. // Uses table of substitutions for similar letters
  2514. let selectNodeByTextContent = (()=> {
  2515. let subs = {
  2516. // english & greek
  2517. 'А': 'AΑ', 'В': 'BΒ', 'Г':'Γ',
  2518. 'Е': 'EΕ', 'З': '3', 'К':'KΚ',
  2519. 'М': 'MΜ', 'Н': 'HΗ', 'О':'OΟ',
  2520. 'П': 'Π', 'Р': 'PΡ', 'С':'C',
  2521. 'Т': 'T', 'Ф': 'Φ', 'Х':'XΧ'
  2522. }
  2523. let regExpBuilder = text => new RegExp(
  2524. text.toUpperCase()
  2525. .split('')
  2526. .map(function(e){
  2527. return `${e in subs ? `[${e}${subs[e]}]` : (e === ' ' ? '\\s+' : e)}[\u200b\u200c\u200d]*`;
  2528. })
  2529. .join(''),
  2530. 'i');
  2531. let reMap = {};
  2532. return (re, opts = { root: _document.body }) => {
  2533. if (!re.test) {
  2534. if (!reMap[re])
  2535. reMap[re] = regExpBuilder(re);
  2536. re = reMap[re];
  2537. }
  2538.  
  2539. for (let child of opts.root.children)
  2540. if (re.test(child.textContent)) {
  2541. if (opts.shallow)
  2542. return child;
  2543. opts.root = child;
  2544. return selectNodeByTextContent(re, opts) || child;
  2545. }
  2546. }
  2547. })();
  2548.  
  2549. // webpackJsonp filter
  2550. function webpackJsonpFilter(blacklist, log = false) {
  2551. let _apply = Reflect.apply;
  2552. let _toString = Function.prototype.call.bind(Function.prototype.toString);
  2553. function wrapPush(webpack) {
  2554. let _push = webpack.push.bind(webpack);
  2555. Object.defineProperty(webpack, 'push', {
  2556. get: () => _push,
  2557. set: vl => {
  2558. _push = new Proxy(vl, {
  2559. apply: (push, obj, args) => {
  2560. wrapper: {
  2561. if (!(args[0] instanceof Array))
  2562. break wrapper;
  2563. let mainName;
  2564. if (args[0][2] instanceof Array && args[0][2][0] instanceof Array)
  2565. mainName = args[0][2][0][0];
  2566. let funs = args[0][1];
  2567. if (!(funs instanceof Object && !(funs instanceof Array)))
  2568. break wrapper;
  2569. for (let name in funs) {
  2570. if (typeof funs[name] !== 'function')
  2571. continue;
  2572. if (blacklist.test(_toString(funs[name])) && name !== mainName) {
  2573. let text = log ? _toString(funs[name]) : '';
  2574. funs[name] = () => _console.log(`Skip webpack ${name}`, text);
  2575. }
  2576. }
  2577. }
  2578. _console.log('webpack.push()');
  2579. return _apply(push, obj, args);
  2580. }
  2581. });
  2582. return true;
  2583. }
  2584. });
  2585. return webpack
  2586. }
  2587. let _webpackJsonp = wrapPush([]);
  2588. Object.defineProperty(win, 'webpackJsonp', {
  2589. get: () => _webpackJsonp,
  2590. set: vl => {
  2591. if (vl === _webpackJsonp)
  2592. return;
  2593. _console.log('new webpackJsonp', vl);
  2594. _webpackJsonp = wrapPush(vl);
  2595. return true;
  2596. }
  2597. });
  2598. }
  2599.  
  2600. // === Scripts for specific domains ===
  2601.  
  2602. let scripts = {};
  2603. // prevent popups and redirects block
  2604. // Popups
  2605. scripts.preventPopups = {
  2606. other: 'biqle.ru, chaturbate.com, dfiles.ru, eporner.eu, hentaiz.org, mirrorcreator.com, online-multy.ru' +
  2607. 'radikal.ru, rumedia.ws, tapehub.tech, thepiratebay.org, unionpeer.com, zippyshare.com',
  2608. now: preventPopups
  2609. };
  2610. // Popunders (background redirect)
  2611. scripts.preventPopunders = {
  2612. other: 'lostfilm-online.ru, mediafire.com, megapeer.org, megapeer.ru, perfectgirls.net',
  2613. now: preventPopunders
  2614. };
  2615. // PopMix (both types of popups encountered on site)
  2616. scripts['openload.co'] = {
  2617. other: 'oload.tv, oload.info',
  2618. now: () => {
  2619. nt.define('CNight', win.CoinHive);
  2620. if (location.pathname.startsWith('/embed/')) {
  2621. nt.define('BetterJsPop', {
  2622. add: ((a, b) => _console.trace('BetterJsPop.add(%o, %o)', a, b)),
  2623. config: ((o) => _console.trace('BetterJsPop.config(%o)', o)),
  2624. Browser: { isChrome: true }
  2625. });
  2626. nt.define('isSandboxed', nt.func(null));
  2627. nt.define('adblock', false);
  2628. nt.define('adblock2', false);
  2629. } else preventPopMix();
  2630. }
  2631. };
  2632. scripts['turbobit.net'] = preventPopMix;
  2633.  
  2634. scripts['tapochek.net'] = () => {
  2635. // workaround for moradu.com/apu.php load error handler script, not sure which ad network is this
  2636. let _appendChild = Object.getOwnPropertyDescriptor(_Node, 'appendChild');
  2637. let _appendChild_value = _appendChild.value;
  2638. _appendChild.value = function appendChild(node) {
  2639. if (this === _document.body)
  2640. if ((node instanceof HTMLScriptElement || node instanceof HTMLStyleElement) &&
  2641. /^https?:\/\/[0-9a-f]{15}\.com\/\d+(\/|\.css)$/.test(node.src) ||
  2642. node instanceof HTMLDivElement && node.style.zIndex > 900000 &&
  2643. node.style.backgroundImage.includes('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'))
  2644. throw '...eenope!';
  2645. return _appendChild_value.apply(this, arguments);
  2646. };
  2647. Object.defineProperty(_Node, 'appendChild', _appendChild);
  2648.  
  2649. // disable window focus tricks and changing location
  2650. let focusHandlerName = /\WfocusAchieved\(/
  2651. let _toString = Function.prototype.call.bind(Function.prototype.toString);
  2652. let _setInterval = win.setInterval;
  2653. win.setInterval = (...args) => {
  2654. if (args.length && focusHandlerName.test(_toString(args[0]))) {
  2655. _console.log('skip setInterval for', ...args);
  2656. return -1;
  2657. }
  2658. return _setInterval(...args);
  2659. };
  2660. let _addEventListener = win.addEventListener;
  2661. win.addEventListener = function(...args) {
  2662. if (args.length && args[0] === 'focus' && focusHandlerName.test(_toString(args[1]))) {
  2663. _console.log('skip addEventListener for', ...args);
  2664. return undefined;
  2665. }
  2666. return _addEventListener.apply(this, args);
  2667. };
  2668.  
  2669. // generic popup prevention
  2670. preventPopups();
  2671. };
  2672.  
  2673. scripts['rustorka.com'] = {
  2674. other: 'rustorka.club, rustorka.innal.top, rustorka.lib, rustorka.net',
  2675. now: () => scriptLander(() => {
  2676. selectiveEval(evalPatternGeneric, /antiadblock/);
  2677. selectiveCookies('adblock|u_count|gophp|st2|st3', ['/forum']);
  2678. abortExecution(onAccess.InlineScript, 'ads_script');
  2679. }, selectiveEval, selectiveCookies, abortExecutionModule)
  2680. };
  2681.  
  2682. // = other ======================================================================================
  2683. scripts['1tv.ru'] = {
  2684. other: 'mediavitrina.ru',
  2685. now: () => scriptLander(() => {
  2686. nt.define('EUMPAntiblockConfig', nt.proxy({url: '//www.1tv.ru/favicon.ico'}));
  2687. nt.define('preroll', false);
  2688.  
  2689. let _EUMP = undefined;
  2690. const _EUMP_set = x => {
  2691. if (x === _EUMP)
  2692. return true;
  2693. let _plugins = x.plugins;
  2694. Object.defineProperty(x, 'plugins', {
  2695. enumerable: true,
  2696. get: () => { return _plugins; },
  2697. set: vl => {
  2698. if (vl === _plugins)
  2699. return true;
  2700. nt.defineOn(vl, 'antiblock', function(player, opts) {
  2701. const antiblock = nt.proxy({
  2702. opts: opts,
  2703. readyState: 'ready',
  2704. isEUMPPlugin: true,
  2705. detected: nt.func(false, 'antiblock.detected'),
  2706. currentWeight: nt.func(0, 'antiblock.currentWeight')
  2707. });
  2708. player.antiblock = antiblock;
  2709. return antiblock;
  2710. }, 'EUMP.plugins.');
  2711. nt.defineOn(vl, 'timelineactions', function(player, opts) {
  2712. const timelineactions = nt.proxy({
  2713. opts: opts,
  2714. readyState: 'ready',
  2715. isEUMPPlugin: true
  2716. });
  2717. player.timelineactions = timelineactions;
  2718. return timelineactions;
  2719. }, 'EUMP.plugins.');
  2720. _plugins = vl;
  2721. return true;
  2722. }
  2723. });
  2724. _EUMP = x;
  2725. return true;
  2726. };
  2727. if ('EUMP' in win)
  2728. _EUMP_set(win.EUMP);
  2729. Object.defineProperty(win, 'EUMP', {
  2730. enumerable: true,
  2731. get: () => _EUMP,
  2732. set: _EUMP_set
  2733. });
  2734.  
  2735. let _EUMPVGTRK = undefined;
  2736. const _EUMPVGTRK_set = x => {
  2737. if (x === _EUMPVGTRK)
  2738. return true;
  2739. if (x && x.prototype) {
  2740. if ('generatePrerollUrls' in x.prototype)
  2741. nt.defineOn(x.prototype, 'generatePrerollUrls', nt.func(null, 'EUMPVGTRK.generatePrerollUrls'), 'EUMPVGTRK.prototype.', false);
  2742. if ('sendAdsEvent' in x.prototype)
  2743. nt.defineOn(x.prototype, 'sendAdsEvent', nt.func(null, 'EUMPVGTRK.sendAdsEvent'), 'EUMPVGTRK.prototype.', false);
  2744. }
  2745. _EUMPVGTRK = x;
  2746. return true;
  2747. }
  2748. if ('EUMPVGTRK' in win)
  2749. _EUMPVGTRK_set(win.EUMPVGTRK)
  2750. Object.defineProperty(win, 'EUMPVGTRK', {
  2751. enumerable: true,
  2752. get: () => _EUMPVGTRK,
  2753. set: _EUMPVGTRK_set
  2754. })
  2755. }, nullTools)
  2756. };
  2757.  
  2758. scripts['24smi.org'] = () => scriptLander(() => selectiveCookies('has_adblock'), selectiveCookies);
  2759.  
  2760. scripts['2picsun.ru'] = {
  2761. other: 'pics2sun.ru, 3pics-img.ru',
  2762. now: () => {
  2763. Object.defineProperty(navigator, 'userAgent', {value: 'googlebot'});
  2764. }
  2765. };
  2766.  
  2767. scripts['4pda.ru'] = {
  2768. now: () => {
  2769. // https://greasyfork.org/en/scripts/14470-4pda-unbrender
  2770. let isForum = location.pathname.startsWith('/forum/'),
  2771. remove = node => (node && node.parentNode.removeChild(node)),
  2772. hide = node => (node && (node.style.display = 'none'));
  2773.  
  2774. // clean a page
  2775. window.addEventListener(
  2776. 'DOMContentLoaded', function() {
  2777. let width = () => window.innerWidth || _de.clientWidth || _document.body.clientWidth || 0;
  2778. let height = () => window.innerHeight || _de.clientHeight || _document.body.clientHeight || 0;
  2779.  
  2780. HeaderAds: {
  2781. // hide ads above HEADER
  2782. let nav = _document.querySelector('.menu');
  2783. if (!nav) {
  2784. _console.warn('Unable to locate header element');
  2785. break HeaderAds;
  2786. }
  2787. for (let itm of nav.parentNode.children)
  2788. if (itm !== nav)
  2789. hide(itm);
  2790. else break;
  2791. }
  2792.  
  2793. if (isForum) {
  2794. let itm = _document.querySelector('#logostrip');
  2795. if (itm)
  2796. remove(itm.parentNode.nextSibling);
  2797. // clear background in the download frame
  2798. if (location.pathname.startsWith('/forum/dl/')) {
  2799. let setBackground = node => _setAttribute(
  2800. node,
  2801. 'style', (_getAttribute(node, 'style') || '') +
  2802. ';background-color:#4ebaf6!important'
  2803. );
  2804. setBackground(_document.body);
  2805. for (let itm of _document.querySelectorAll('body > div'))
  2806. if (!itm.querySelector('.dw-fdwlink, .content') && !itm.classList.contains('footer'))
  2807. remove(itm);
  2808. else
  2809. setBackground(itm);
  2810. }
  2811. // exist from DOMContentLoaded since the rest is not for forum
  2812. return;
  2813. }
  2814.  
  2815. FixNavMenu: {
  2816. // hide ad link from the navigation
  2817. let ad = _document.querySelector('.menu-main-item > a > svg');
  2818. if (!ad) {
  2819. _console.warn('Unable to locate menu ad item');
  2820. break FixNavMenu;
  2821. } else {
  2822. ad = ad.parentNode.parentNode;
  2823. hide(ad);
  2824. }
  2825. }
  2826. SidebarAds: {
  2827. // remove ads from sidebar
  2828. let aside = _document.querySelectorAll('[class]:not([id]) > [id]:not([class]) > :first-child + :last-child:not(.v-panel)');
  2829. if (!aside.length) {
  2830. _console.warn('Unable to locate sidebar');
  2831. break SidebarAds;
  2832. }
  2833. let post;
  2834. for (let side of aside) {
  2835. _console.log('Processing potential sidebar:', side);
  2836. for (let itm of Array.from(side.children)) {
  2837. post = itm.classList.contains('post');
  2838. if (itm.querySelector('iframe') && !post)
  2839. remove(itm);
  2840. if (itm.querySelector('script, a[target="_blank"] > img') && !post || !itm.children.length)
  2841. hide(itm);
  2842. }
  2843. }
  2844. }
  2845.  
  2846. _document.body.setAttribute('style', (_document.body.getAttribute('style')||'')+';background-color:#E6E7E9!important');
  2847.  
  2848. let extra = 'background-image:none!important;background-color:transparent!important',
  2849. fakeStyles = new WeakMap(),
  2850. styleProxy = {
  2851. get: (target, prop) => fakeStyles.get(target)[prop] || target[prop],
  2852. set: function(target, prop, value) {
  2853. let fakeStyle = fakeStyles.get(target);
  2854. ((prop in fakeStyle) ? fakeStyle : target)[prop] = value;
  2855. return true;
  2856. }
  2857. };
  2858. for (let itm of _document.querySelectorAll('[id]:not(A), A')) {
  2859. if (!(itm.offsetWidth > 0.95 * width() &&
  2860. itm.offsetHeight > 0.85 * height()))
  2861. continue;
  2862. if (itm.tagName !== 'A') {
  2863. fakeStyles.set(itm.style, {
  2864. 'backgroundImage': itm.style.backgroundImage,
  2865. 'backgroundColor': itm.style.backgroundColor
  2866. });
  2867.  
  2868. try {
  2869. Object.defineProperty(itm, 'style', {
  2870. value: new Proxy(itm.style, styleProxy),
  2871. enumerable: true
  2872. });
  2873. } catch (e) {
  2874. _console.log('Unable to protect style property.', e);
  2875. }
  2876.  
  2877. _setAttribute(itm, 'style', `${(_getAttribute(itm, 'style') || '')};${extra}`);
  2878. }
  2879. if (itm.tagName === 'A')
  2880. _setAttribute(itm, 'style', 'display:none!important');
  2881. }
  2882. }
  2883. );
  2884. }
  2885. };
  2886.  
  2887. scripts['adhands.ru'] = () => scriptLander(() => {
  2888. try {
  2889. let _adv;
  2890. Object.defineProperty(win, 'adv', {
  2891. get: () => _adv,
  2892. set: (v) => {
  2893. _console.log('Blocked advert on adhands.ru.');
  2894. nt.defineOn(v, 'advert', '', 'adv.');
  2895. _adv = v;
  2896. }
  2897. });
  2898. } catch (ignore) {
  2899. if (!win.adv)
  2900. _console.log('Unable to locate advert on adhands.ru.');
  2901. else {
  2902. _console.log('Blocked advert on adhands.ru.');
  2903. nt.define('adv.advert', '');
  2904. }
  2905. }
  2906. }, nullTools);
  2907.  
  2908. scripts['all-episodes.tv'] = () => {
  2909. nt.define('perX1', 2);
  2910. createStyle('#advtss, #ad3, a[href*="/ad.admitad.com/"] { display:none!important }');
  2911. };
  2912.  
  2913. scripts['allhentai.ru'] = () => {
  2914. preventPopups();
  2915. scriptLander(() => {
  2916. selectiveEval();
  2917. let _onerror = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onerror');
  2918. if (!_onerror)
  2919. return;
  2920. _onerror.set = (...args) => _console.log(args[0].toString());
  2921. Object.defineProperty(HTMLElement.prototype, 'onerror', _onerror);
  2922. }, selectiveEval);
  2923. };
  2924.  
  2925. scripts['allmovie.pro'] = {
  2926. other: 'rufilmtv.org',
  2927. dom: function() {
  2928. // pretend to be Android to make site use different played for ads
  2929. if (isSafari)
  2930. return;
  2931. Object.defineProperty(navigator, 'userAgent', {
  2932. get: function(){
  2933. 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';
  2934. },
  2935. enumerable: true
  2936. });
  2937. }
  2938. };
  2939.  
  2940. scripts['anidub-online.ru'] = {
  2941. other: 'anime.anidub.com, online.anidub.com',
  2942. dom: function() {
  2943. if (win.ogonekstart1)
  2944. win.ogonekstart1 = () => _console.log("Fire in the hole!");
  2945. },
  2946. now: () => createStyle([
  2947. '.background {background: none!important;}',
  2948. '.background > script + div,'+
  2949. '.background > script ~ div:not([id]):not([class]) + div[id][class]'+
  2950. '{display:none!important}'
  2951. ])
  2952. };
  2953.  
  2954. scripts['tv.animebest.org'] = {
  2955. now: () => {
  2956. let _eval = win.eval;
  2957. win.eval = new win.Proxy(win.eval, {
  2958. apply: (evl, ths, args) => {
  2959. if (typeof args[0] === 'string' &&
  2960. args[0].includes("'VASTP'")) {
  2961. args[0] = args[0].replace("'VASTP'", "''");
  2962. win.eval = _eval;
  2963. }
  2964. return Reflect.apply(evl, ths, args);
  2965. }
  2966. });
  2967. }
  2968. };
  2969.  
  2970. scripts['audioportal.su'] = {
  2971. now: () => createStyle('#blink2 { display: none !important }'),
  2972. dom: () => {
  2973. let links = _document.querySelectorAll('a[onclick*="clickme("]');
  2974. if (!links) return;
  2975. for (let link of links)
  2976. clickme(link);
  2977. }
  2978. };
  2979.  
  2980. scripts['avito.ru'] = () => scriptLander(() => selectiveCookies('abp|cmtchd|crookie|is_adblock'), selectiveCookies);
  2981.  
  2982. scripts['di.fm'] = () => scriptLander(() => {
  2983. let log = false;
  2984. // wrap global app object to catch registration of specific modules
  2985. let _di = undefined;
  2986. Object.defineProperty(win, 'di', {
  2987. get: () => _di,
  2988. set: vl => {
  2989. if (vl === _di)
  2990. return;
  2991. log && _console.log('di =', vl);
  2992. _di = new Proxy(vl, {
  2993. set: (di, name, vl) => {
  2994. if (vl === di[name])
  2995. return true;
  2996. if (name === 'app') {
  2997. log && _console.log('di.app =', vl);
  2998. if ('module' in vl)
  2999. vl.module = new Proxy(vl.module, {
  3000. apply: (module, that, args) => {
  3001. if (/Wall|Banner|Detect|WebplayerApp\.Ads/.test(args[0])) {
  3002. let name = args[0];
  3003. log && _console.log('wrap', name, 'module');
  3004. if (typeof args[1] === 'function')
  3005. args[1] = new Proxy(args[1], {
  3006. apply: (fun, that, args) => {
  3007. if (args[0]) // module object
  3008. args[0].start = () => _console.log('Skipped start of', name);
  3009. return Reflect.apply(fun, that, args);
  3010. }
  3011. });
  3012. }// else log && _console.log('loading module', args[0]);
  3013. if (args[0] === 'Modals') {
  3014. log && _console.log('wrap', name, 'module');
  3015. if (typeof args[1] === 'function')
  3016. args[1] = new Proxy(args[1], {
  3017. apply: (fun, that, args) => {
  3018. if ('commands' in args[1] && 'setHandlers' in args[1].commands &&
  3019. !Object.hasOwnProperty.call(args[1].commands, 'setHandlers')) {
  3020. let _commands = args[1].commands;
  3021. _commands.setHandlers = new Proxy(_commands.setHandlers, {
  3022. apply: (fun, that, args) => {
  3023. for (let name in args[0])
  3024. if (name === 'modal:streaminterrupt' ||
  3025. name === 'modal:midroll')
  3026. args[0][name] = () => _console.log('Skipped', name, 'window');
  3027. delete _commands.setHandlers;
  3028. return Reflect.apply(fun, that, args);
  3029. }
  3030. });
  3031. }
  3032. return Reflect.apply(fun, that, args);
  3033. }
  3034. });
  3035. }
  3036. return Reflect.apply(module, that, args);
  3037. }
  3038. });
  3039. }
  3040. di[name] = vl;
  3041. return true;
  3042. }
  3043. });
  3044. }
  3045. });
  3046. // don't send errorception logs
  3047. Object.defineProperty(win, 'onerror', {
  3048. set: vl => log && _console.trace('Skipped global onerror callback %o', vl)
  3049. });
  3050. });
  3051.  
  3052. scripts['draug.ru'] = {
  3053. other: 'vargr.ru',
  3054. now: () => scriptLander(() => {
  3055. if (location.pathname === '/pop.html')
  3056. win.close();
  3057. createStyle([
  3058. '#timer_1 { display: none !important }',
  3059. '#timer_2 { display: block !important }'
  3060. ]);
  3061. let _contentWindow = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, 'contentWindow');
  3062. let _get_contentWindow = Function.prototype.apply.bind(_contentWindow.get);
  3063. _contentWindow.get = function() {
  3064. let res = _get_contentWindow(this);
  3065. if (res.location.href === 'about:blank')
  3066. res.document.write = (...args) => _console.log('Skipped iframe.write(', ...args, ')');
  3067. return res;
  3068. };
  3069. Object.defineProperty(HTMLIFrameElement.prototype, 'contentWindow', _contentWindow);
  3070. }),
  3071. dom: () => {
  3072. let list = _querySelectorAll('div[id^="yandex_rtb_"], .adsbygoogle');
  3073. list.forEach(node => _console.log('Removed:', node.parentNode.parentNode.removeChild(node.parentNode)));
  3074. }
  3075. };
  3076.  
  3077. scripts['drive2.ru'] = () => {
  3078. gardener('.c-block:not([data-metrika="recomm"]),.o-grid__item', />Реклама<\//i);
  3079. scriptLander(() => {
  3080. selectiveCookies();
  3081. let _d2 = undefined;
  3082. Object.defineProperty(win, 'd2', {
  3083. get: () => _d2,
  3084. set: o => {
  3085. if (o === _d2)
  3086. return true;
  3087. _d2 = new Proxy(o, {
  3088. set: (tgt, prop, val) => {
  3089. if (['brandingRender', 'dvReveal', '__dv'].includes(prop))
  3090. val = () => null;
  3091. tgt[prop] = val;
  3092. return true;
  3093. }
  3094. });
  3095. }
  3096. });
  3097. // obfuscated Yandex.Direct
  3098. nt.define('Object.prototype.initYaDirect', undefined);
  3099. }, nullTools, selectiveCookies);
  3100. };
  3101.  
  3102. scripts['echo.msk.ru'] = () => scriptLander(() => {
  3103. selectiveCookies();
  3104. selectiveEval(evalPatternYandex, /^document\.write/, /callAdblock/);
  3105. }, selectiveEval, selectiveCookies);
  3106.  
  3107. scripts['fastpic.ru'] = () => {
  3108. // Had to obfuscate property name to avoid triggering anti-obfuscation on greasyfork.org -_- (Exception 403012)
  3109. nt.define(`_0x${'4955'}`, []);
  3110. };
  3111.  
  3112. scripts['fishki.net'] = () => {
  3113. scriptLander(() => {
  3114. let fishki = {};
  3115. nt.defineOn(fishki, 'adv', nt.proxy({
  3116. afterAdblockCheck: nt.func(null),
  3117. refreshFloat: nt.func(null)
  3118. }), 'fishki.');
  3119. nt.defineOn(fishki, 'is_adblock', false, 'fishki.');
  3120. nt.define('fishki', fishki);
  3121. }, nullTools);
  3122. gardener('.drag_list > .drag_element, .list-view > .paddingtop15, .post-wrap', /543769|Новости\sпартнеров|Полезная\sреклама/);
  3123. };
  3124.  
  3125. scripts['forbes.com'] = () => {
  3126. nt.define('Object.prototype.isAdLight', true);
  3127. nt.define('Object.prototype.adblockPresent', false);
  3128. nt.define('Object.prototype.isAdvertisement', false);
  3129. nt.define('Object.prototype.articleRetracted', false);
  3130. nt.define('Object.prototype.articleIsBlocked', false);
  3131. };
  3132.  
  3133. scripts['friends.in.ua'] = () => scriptLander(() => {
  3134. Object.defineProperty(win, 'need_warning', {
  3135. get: () => 0, set: () => null
  3136. });
  3137. });
  3138.  
  3139. scripts['gamersheroes.com'] = () => abortExecution(onAccess.InlineScript, 'document.createElement', {
  3140. pattern: /window\[\w+\(\[(\d+,?\s?)+\],\s?\w+\)\]/
  3141. });
  3142.  
  3143. scripts['gidonline.club'] = () => createStyle('.tray > div[style] {display: none!important}');
  3144.  
  3145. scripts['hdgo.cc'] = {
  3146. other: '46.30.43.38, couber.be',
  3147. now: () => (new MutationObserver(
  3148. (ms) => {
  3149. let m, node;
  3150. for (m of ms) for (node of m.addedNodes)
  3151. if (node.tagName instanceof HTMLScriptElement && _getAttribute(node, 'onerror') !== null)
  3152. node.removeAttribute('onerror');
  3153. }
  3154. )).observe(_document.documentElement, { childList:true, subtree: true })
  3155. };
  3156.  
  3157. scripts['gamepur.com'] = () => {
  3158. nt.define('ga', nt.func(null));
  3159. win.Object.defineProperty = new Proxy(win.Object.defineProperty, {
  3160. apply: (fun, that, args) => {
  3161. if (typeof args[1] === 'string' &&
  3162. (args[1] === 'hasAdblocker' || args[1] === 'blockerDetected'))
  3163. throw new ReferenceError(`${args[1]} is not defined`);
  3164. return Reflect.apply(fun, that, args);
  3165. }
  3166. });
  3167. };
  3168.  
  3169. scripts['gismeteo.ru'] = {
  3170. other: 'gismeteo.by, gismeteo.kz, gismeteo.md, gismeteo.ua',
  3171. now: () => scriptLander(() => {
  3172. selectiveCookies('ab_[^=]*|redirect|_gab|mkrft');
  3173. gardener('div > script', /AdvManager/i, { observe: true, parent: 'div' });
  3174. // obfuscated Yandex.Direct
  3175. nt.define('Object.prototype.initYaDirect', undefined);
  3176. }, nullTools, selectiveCookies)
  3177. };
  3178.  
  3179. scripts['gorodrabot.ru'] = {
  3180. other: 'sdamgia.ru',
  3181. now: () => scriptLander(() => {
  3182. abortExecution(onAccess.Get, 'Object.prototype.initYaDirect');
  3183. abortExecution(onAccess.Get, 'Object.prototype.initYaContext');
  3184. }, abortExecutionModule)
  3185. };
  3186.  
  3187. scripts['hdrezka.ag'] = () => {
  3188. Object.defineProperty(win, 'ab', { value: false, enumerable: true });
  3189. gardener('div[id][onclick][onmouseup][onmousedown]', /onmouseout/i);
  3190. };
  3191.  
  3192. scripts['hqq.tv'] = () => scriptLander(() => {
  3193. // disable anti-debugging in hqq.tv player
  3194. let isObfuscated = text => /[^a-z0-9]([a-z0-9]{1,2}\.[a-z0-9]{1,2}\(|[a-z0-9]{4}\.[a-z]\(\d+\)|[a-z0-9]\[[a-z0-9]{1,2}\]\[[a-z0-9]{1,2}\])/i.test(text);
  3195. deepWrapAPI(root => {
  3196. // skip obfuscated stuff and a few other calls
  3197. let _setInterval = root.setInterval,
  3198. _setTimeout = root.setTimeout,
  3199. _toString = root.Function.prototype.call.bind(root.Function.prototype.toString);
  3200. root.setInterval = (...args) => {
  3201. let fun = args[0];
  3202. if (fun instanceof Function) {
  3203. let text = _toString(fun),
  3204. skip = text.includes('check();') || isObfuscated(text);
  3205. _console.trace('setInterval %o skip %o', text, skip);
  3206. if (skip) return -1;
  3207. }
  3208. return _setInterval.apply(this, args);
  3209. };
  3210. let wrappedST = new WeakSet();
  3211. root.setTimeout = (...args) => {
  3212. let fun = args[0];
  3213. if (fun instanceof Function) {
  3214. let text = _toString(fun),
  3215. skip = fun.name === 'check' || isObfuscated(text);
  3216. if (!wrappedST.has(fun)) {
  3217. _console.trace('setTimeout %o skip %o', text, skip);
  3218. wrappedST.add(fun);
  3219. }
  3220. if (skip) return;
  3221. }
  3222. return _setTimeout.apply(this, args);
  3223. };
  3224. // skip 'debugger' call
  3225. let _eval = root.eval;
  3226. root.eval = text => {
  3227. if (typeof text === 'string' && text.includes('debugger;')) {
  3228. _console.trace('skip eval %o', text);
  3229. return;
  3230. }
  3231. _eval(text);
  3232. };
  3233. // Prevent RegExpt + toString trick
  3234. let _proto = undefined;
  3235. try {
  3236. _proto = root.RegExp.prototype;
  3237. } catch(ignore) {
  3238. return;
  3239. }
  3240. let _RE_tS = Object.getOwnPropertyDescriptor(_proto, 'toString');
  3241. let _RE_tSV = _RE_tS.value || _RE_tS.get();
  3242. Object.defineProperty(_proto, 'toString', {
  3243. enumerable: _RE_tS.enumerable,
  3244. configurable: _RE_tS.configurable,
  3245. get: () => _RE_tSV,
  3246. set: val => _console.trace('Attempt to change toString for %o with %s', this, _toString(val))
  3247. });
  3248. });
  3249. }, deepWrapAPI);
  3250.  
  3251. scripts['hideip.me'] = {
  3252. now: () => scriptLander(() => {
  3253. let _innerHTML = Object.getOwnPropertyDescriptor(_Element, 'innerHTML');
  3254. let _set_innerHTML = _innerHTML.set;
  3255. let _innerText = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'innerText');
  3256. let _get_innerText = _innerText.get;
  3257. let div = _document.createElement('div');
  3258. _innerHTML.set = function(...args) {
  3259. _set_innerHTML.call(div, args[0].replace('i','a'));
  3260. if (args[0] && /[рp][еe]кл/.test(_get_innerText.call(div))||
  3261. /(\d\d\d?\.){3}\d\d\d?:\d/.test(_get_innerText.call(this)) ) {
  3262. _console.log('Anti-Adblock killed.');
  3263. return true;
  3264. }
  3265. _set_innerHTML.apply(this, args);
  3266. };
  3267. Object.defineProperty(_Element, 'innerHTML', _innerHTML);
  3268. Object.defineProperty(win, 'adblock', {
  3269. get: () => false,
  3270. set: () => null,
  3271. enumerable: true
  3272. });
  3273. let _$ = {};
  3274. let _$_map = new WeakMap();
  3275. let _gOPD = Object.getOwnPropertyDescriptor(Object, 'getOwnPropertyDescriptor');
  3276. let _val_gOPD = _gOPD.value;
  3277. _gOPD.value = function(...args) {
  3278. let _res = _val_gOPD.apply(this, args);
  3279. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery')) {
  3280. delete _res.get;
  3281. delete _res.set;
  3282. _res.value = win[args[1]];
  3283. }
  3284. return _res;
  3285. };
  3286. Object.defineProperty(Object, 'getOwnPropertyDescriptor', _gOPD);
  3287. let getJQWrap = (n) => {
  3288. let name = n;
  3289. return {
  3290. enumerable: true,
  3291. get: () => _$[name],
  3292. set: x => {
  3293. if (_$_map.has(x)) {
  3294. _$[name] = _$_map.get(x);
  3295. return true;
  3296. }
  3297. if (x === _$.$ || x === _$.jQuery) {
  3298. _$[name] = x;
  3299. return true;
  3300. }
  3301. _$[name] = new Proxy(x, {
  3302. apply: (t, o, args) => {
  3303. let _res = t.apply(o, args);
  3304. if (_$_map.has(_res.is))
  3305. _res.is = _$_map.get(_res.is);
  3306. else {
  3307. let _is = _res.is;
  3308. _res.is = function(...args) {
  3309. if (args[0] === ':hidden')
  3310. return false;
  3311. return _is.apply(this, args);
  3312. };
  3313. _$_map.set(_is, _res.is);
  3314. }
  3315. return _res;
  3316. }
  3317. });
  3318. _$_map.set(x, _$[name]);
  3319. return true;
  3320. }
  3321. };
  3322. };
  3323. Object.defineProperty(win, '$', getJQWrap('$'));
  3324. Object.defineProperty(win, 'jQuery', getJQWrap('jQuery'));
  3325. let _dP = Object.defineProperty;
  3326. Object.defineProperty = function(...args) {
  3327. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery'))
  3328. return undefined;
  3329. return _dP.apply(this, args);
  3330. };
  3331. })
  3332. };
  3333.  
  3334. scripts['igra-prestoloff.cx'] = () => scriptLander(() => {
  3335. /*jslint evil: true */ // yes, evil, I know
  3336. let _write = _document.write.bind(_document);
  3337. /*jslint evil: false */
  3338. nt.define('document.write', t => {
  3339. let id = t.match(/jwplayer\("(\w+)"\)/i);
  3340. if (id && id[1])
  3341. return _write(`<div id="${id[1]}"></div>${t}`);
  3342. return _write('');
  3343. }, true);
  3344. });
  3345.  
  3346. scripts['imageban.ru'] = () => { Object.defineProperty(win, 'V7x1J', { get: () => null }); };
  3347.  
  3348. scripts['inoreader.com'] = () => scriptLander(() => {
  3349. let i = setInterval(() => {
  3350. if ('adb_detected' in win) {
  3351. win.adb_detected = () => adb_not_detected();
  3352. clearInterval(i);
  3353. }
  3354. }, 10);
  3355. _document.addEventListener('DOMContentLoaded', () => clearInterval(i), false);
  3356. });
  3357.  
  3358. scripts['ivi.ru'] = () => {
  3359. let _xhr_open = win.XMLHttpRequest.prototype.open;
  3360. win.XMLHttpRequest.prototype.open = function(method, url, ...args) {
  3361. if (typeof url === 'string')
  3362. if (url.endsWith('/track'))
  3363. return;
  3364. return _xhr_open.call(this, method, url, ...args);
  3365. };
  3366. let _responseText = Object.getOwnPropertyDescriptor(XMLHttpRequest.prototype, 'responseText');
  3367. let _responseText_get = _responseText.get;
  3368. _responseText.get = function() {
  3369. if (this.__responseText__)
  3370. return this.__responseText__;
  3371. let res = _responseText_get.apply(this, arguments);
  3372. let o;
  3373. try {
  3374. if (res)
  3375. o = JSON.parse(res);
  3376. } catch(ignore) {};
  3377. let changed = false;
  3378. if (o && o.result) {
  3379. if (o.result instanceof Array &&
  3380. 'adv_network_logo_url' in o.result[0]) {
  3381. o.result = [];
  3382. changed = true;
  3383. }
  3384. if (o.result.show_adv) {
  3385. o.result.show_adv = false;
  3386. changed = true;
  3387. }
  3388. }
  3389. if (changed) {
  3390. _console.log('changed response >>', o);
  3391. res = JSON.stringify(o);
  3392. }
  3393. this.__responseText__ = res;
  3394. return res;
  3395. };
  3396. Object.defineProperty(XMLHttpRequest.prototype, 'responseText', _responseText);
  3397. };
  3398.  
  3399. scripts['kakprosto.ru'] = () => scriptLander(() => {
  3400. selectiveCookies('yadb');
  3401. abortExecution(onAccess.InlineScript, 'yaProxy', { pattern: /yadb/ });
  3402. abortExecution(onAccess.InlineScript, 'yandexContextAsyncCallbacks');
  3403. abortExecution(onAccess.InlineScript, 'adfoxAsyncParams');
  3404. abortExecution(onAccess.InlineScript, 'adfoxBackGroundLoaded');
  3405. }, selectiveCookies, abortExecutionModule);
  3406.  
  3407. scripts['kinopoisk.ru'] = () => {
  3408. // filter cookies
  3409. // set no-branding body style and adjust other blocks on the page
  3410. let style = [
  3411. '.app__header.app__header_margin-bottom_brand, #top { margin-bottom: 20px !important }',
  3412. '.app__branding { display: none !important}'
  3413. ];
  3414. if (location.hostname === 'www.kinopoisk.ru' && !location.pathname.startsWith('/games/'))
  3415. style.push('html:not(#id), body:not(#id), .app-container { background: #d5d5d5 url(/images/noBrandBg.jpg) 50% 0 no-repeat !important }');
  3416. createStyle(style);
  3417. scriptLander(() => {
  3418. selectiveCookies('cmtchd|crookie|kpunk')
  3419. // filter JSON
  3420. const _apply = Reflect.apply;
  3421. win.JSON.parse = new Proxy(win.JSON.parse, {
  3422. apply (fun, that, args) {
  3423. let o = _apply(fun, that, args);
  3424. let name = 'antiAdBlockCookieName';
  3425. if (name in o && typeof o[name] === 'string')
  3426. selectiveCookies(o[name]);
  3427. name = 'branding';
  3428. if (name in o) o[name] = {};
  3429. // tricks against ads in the trailer player
  3430. // if (location.hostname.startsWith('widgets.'))
  3431. if (o.page && o.page.playerParams)
  3432. delete o.page.playerParams.adConfig;
  3433. if (o.common && o.common.bunker && o.common.bunker.adv && o.common.bunker.adv.filmIdWithoutAd)
  3434. o.common.bunker.adv.filmIdWithoutAd.includes = () => true;
  3435. //_console.log('JSON.parse', o);
  3436. return o;
  3437. }
  3438. });
  3439. // skip timeout check for blocked requests
  3440. const _toString = Function.prototype.apply.bind(Function.prototype.toString);
  3441. win.setTimeout = new Proxy(win.setTimeout, {
  3442. apply(fun, that, args) {
  3443. if (args[1] === 100) {
  3444. let str = _toString(args[0]);
  3445. if (str.endsWith('{a()}') || str.endsWith('{n()}'))
  3446. return;
  3447. }
  3448. return _apply(fun, that, args);
  3449. }
  3450. });
  3451. // obfuscated Yandex.Direct
  3452. nt.define('Object.prototype.initYaDirect', undefined);
  3453. nt.define('Object.prototype._resolveDetectResult', () => null);
  3454. nt.define('Object.prototype.detectResultPromise', new Promise(r => r(false)));
  3455. // catch branding and other things
  3456. let _KP = undefined;
  3457. Object.defineProperty(win, 'KP', {
  3458. get: () => _KP,
  3459. set: val => {
  3460. if (_KP === val)
  3461. return true;
  3462. _KP = new Proxy(val, {
  3463. set: (kp, name, val) => {
  3464. if (name === 'branding') {
  3465. kp[name] = new Proxy({ weborama: {} }, {
  3466. get: (kp, name) => name in kp ? kp[name] : '',
  3467. set: () => true
  3468. });
  3469. return true;
  3470. }
  3471. if (name === 'config')
  3472. val = new Proxy(val, {
  3473. set: (cfg, name, val) => {
  3474. if (name === 'anContextUrl')
  3475. return true;
  3476. if (name === 'adfoxEnabled' || name === 'hasBranding')
  3477. val = false;
  3478. if (name === 'adfoxVideoAdUrls')
  3479. val = {flash:{}, html:{}};
  3480. cfg[name] = val;
  3481. return true;
  3482. }
  3483. });
  3484. kp[name] = val;
  3485. return true;
  3486. }
  3487. });
  3488. _console.log('KP =', val);
  3489. }
  3490. });
  3491. }, selectiveCookies, nullTools);
  3492. };
  3493.  
  3494. scripts['korrespondent.net'] = {
  3495. now: () => scriptLander(() => {
  3496. nt.define('holder', function(id) {
  3497. let div = _document.getElementById(id);
  3498. if (!div)
  3499. return;
  3500. if (div.parentNode.classList.contains('col__sidebar')) {
  3501. div.parentNode.appendChild(div);
  3502. div.style.height = '300px';
  3503. }
  3504. });
  3505. }, nullTools),
  3506. dom: () => {
  3507. for (let frame of _document.querySelectorAll('.unit-side-informer > iframe'))
  3508. frame.parentNode.style.width = '1px';
  3509. }
  3510. };
  3511.  
  3512. scripts['liveinternet.ru'] = () => scriptLander(() => {
  3513. selectiveEval(evalPatternYandex);
  3514. selectiveCookies('bltsr|blcrm');
  3515. }, selectiveEval, selectiveCookies);
  3516.  
  3517. scripts['livejournal.com'] = () => scriptLander(() => {
  3518. nt.define('Object.prototype.Adf', undefined);
  3519. }, nullTools);
  3520.  
  3521. scripts['mail.ru'] = {
  3522. other: 'ok.ru, sportmail.ru',
  3523. now: () => scriptLander(() => {
  3524. selectiveCookies('act|testcookie');
  3525. let _hostparts = location.hostname.split('.');
  3526. let _subdomain = _hostparts.slice(-3).join('.');
  3527. let _hostname = _hostparts.slice(-2).join('.');
  3528. let _emailru = _subdomain === 'e.mail.ru' || _subdomain === 'octavius.mail.ru';
  3529. let _mymailru = _subdomain === 'my.mail.ru';
  3530. // setTimeout filter
  3531. let pattern = /advBlock|rbParams/i;
  3532. let _toString = Function.prototype.call.bind(Function.prototype.toString);
  3533. let _setTimeout = Function.prototype.apply.bind(win.setTimeout);
  3534. win.setTimeout = function setTimeout(...args) {
  3535. let text = _toString(args[0]);
  3536. if (pattern.test(text)) {
  3537. _console.trace('Skipped setTimeout: %o', text);
  3538. return;
  3539. }
  3540. return _setTimeout(this, args);
  3541. };
  3542.  
  3543. // Trick to prevent mail.ru from removing 3rd-party styles
  3544. nt.define('Object.prototype.restoreVisibility', nt.func(null));
  3545. // Other Yandex Direct and other ads
  3546. nt.define('Object.prototype.initMimic', undefined);
  3547. nt.define('Object.prototype.hpConfig', undefined);
  3548. nt.define('Object.prototype.direct', undefined);
  3549. nt.define('Object.prototype.getAds', undefined);
  3550. nt.define('rb_counter', nt.func(null, 'rb_counter'));
  3551. if (_hostname === 'mail.ru') {
  3552. if (_subdomain === _hostname)
  3553. nt.define('Object.prototype.baits', undefined);
  3554. if (_mymailru)
  3555. nt.define('Object.prototype.runMimic', nt.func(null));
  3556. }
  3557. if (!_emailru && !_mymailru) {
  3558. nt.define('Object.prototype.mimic', undefined);
  3559. let xray = function xray(){};
  3560. xray[Symbol.toStringTag] = 'xray';
  3561. xray.verbose = false;
  3562. xray.radarPrefix = null;
  3563. xray.xrayRadarUrl = undefined;
  3564. xray.defaultParams = nt.proxy({i: undefined, p: 'media'});
  3565. nt.define('Object.prototype.xray', nt.proxy(xray));
  3566. }
  3567. // banners on ok.ru and counter
  3568. nt.define('getAdvTargetParam', nt.func(null, 'getAdvTargetParam'));
  3569. // shenanigans against ok.ru ABP detector
  3570. if (_hostname === 'ok.ru')
  3571. abortExecution(onAccess.Get, 'OK.hooks');
  3572. // news.mail.ru and sportmail.ru
  3573. abortExecution(onAccess.Get, 'myWidget');
  3574. // cleanup e.mail.ru configs and mimic config on news and sport
  3575. const _apply = Reflect.apply;
  3576. const emptyString = (root, name) => root[name] && (root[name] = '');
  3577. const detectMimic = /direct|240x400|SlotView/;
  3578. win.JSON.parse = new Proxy(win.JSON.parse, {
  3579. apply (fun, that, args) {
  3580. let o = _apply(fun, that, args);
  3581. if (o && typeof o === 'object') {
  3582. if (o.cfg && o.cfg.sotaFeatures) {
  3583. let root = o.cfg.sotaFeatures;
  3584. if (Array.isArray(root.adv)) root.adv = [];
  3585. for (let name in root)
  3586. if (name.startsWith('adv-') || name.startsWith('adman-'))
  3587. delete root[name];
  3588. [ 'email_logs_to', 'smokescreen-locators'
  3589. ].forEach(name => emptyString(root, name));
  3590. }
  3591. if (o.userConfig) {
  3592. if (Array.isArray(o.userConfig.honeypot))
  3593. o.userConfig.honeypot.forEach((v, id, me) => (me[id] = []));
  3594. const cfg = o.userConfig.config;
  3595. if (cfg && cfg.honeypot)
  3596. emptyString(cfg.honeypot, 'baits');
  3597. }
  3598. if (o.body) {
  3599. const flags = o.body.common_purpose_flags;
  3600. if (flags && 'hide_ad_in_mail_web' in flags)
  3601. flags.hide_ad_in_mail_web = true;
  3602. if (o.body.show_me_ads)
  3603. o.body.show_me_ads = false;
  3604. }
  3605. //_console.log('JSON.parse', o);
  3606. }
  3607. if (Array.isArray(o))
  3608. if (o.some(t => typeof t === 'string' && detectMimic.test(t))) {
  3609. _console.log('Replaced', o);
  3610. o = [];
  3611. } //else _console.log('JSON.parse', o);
  3612. return o;
  3613. }
  3614. });
  3615. // all the rest is only needed on main page and in emails
  3616. if (_subdomain !== 'mail.ru' && !_emailru)
  3617. return;
  3618.  
  3619. // Disable page scrambler on mail.ru to let extensions easily block ads there
  3620. let logger = {
  3621. apply: (target, thisArg, args) => {
  3622. let res = target.apply(thisArg, args);
  3623. _console.log(`${target._name}(`, ...args, `)\n>>`, res);
  3624. return res;
  3625. }
  3626. };
  3627.  
  3628. function wrapLocator(locator) {
  3629. if ('setup' in locator) {
  3630. let _setup = locator.setup;
  3631. locator.setup = function(o) {
  3632. if ('enable' in o) {
  3633. o.enable = false;
  3634. _console.log('Disable mimic mode.');
  3635. }
  3636. if ('links' in o) {
  3637. o.links = [];
  3638. _console.log('Call with empty list of sheets.');
  3639. }
  3640. return _setup.call(this, o);
  3641. };
  3642. locator.insertSheet = () => false;
  3643. locator.wrap = () => false;
  3644. }
  3645. try {
  3646. let names = [];
  3647. for (let name in locator)
  3648. if (locator[name] instanceof Function && name !== 'transform') {
  3649. locator[name]._name = "locator." + name;
  3650. locator[name] = new Proxy(locator[name], logger);
  3651. names.push(name);
  3652. }
  3653. _console.log(`[locator] wrapped properties: ${names.length ? names.join(', ') : '[empty]'}`);
  3654. } catch(e) {
  3655. _console.log(e);
  3656. }
  3657. return locator;
  3658. }
  3659.  
  3660. function defineLocator(root) {
  3661. let _locator = root.locator;
  3662. let wrapLocatorSetter = vl => _locator = wrapLocator(vl);
  3663. let loc_desc = Object.getOwnPropertyDescriptor(root, 'locator');
  3664. if (!loc_desc || loc_desc.set !== wrapLocatorSetter)
  3665. try {
  3666. Object.defineProperty(root, 'locator', {
  3667. set: wrapLocatorSetter,
  3668. get: () => _locator
  3669. });
  3670. } catch (err) {
  3671. _console.log('Unable to redefine "locator" object!!!', err);
  3672. }
  3673. if (loc_desc.value)
  3674. _locator = wrapLocator(loc_desc.value);
  3675. }
  3676.  
  3677. {
  3678. const missingCheck = {
  3679. get: (obj, name) => {
  3680. if (!(name in obj))
  3681. _console.trace('%o missing: %s', obj, name);
  3682. return obj[name];
  3683. }
  3684. };
  3685. const skipLog = (name, ret) => (...args) => (_console.log(`Skip ${name}(`, ...args, ')'), ret);
  3686. const createSkipAllObject = (baseName, obj = {}) => new Proxy(obj, {
  3687. get: (o, name) => {
  3688. if (name in o)
  3689. return o[name];
  3690. _console.log(`Created stub for "${name}" in ${baseName}.`);
  3691. o[name] = skipLog(`${baseName}.${name}`);
  3692. return o[name];
  3693. },
  3694. set: () => true
  3695. });
  3696. const _apply = Reflect.apply;
  3697. const redefiner = {
  3698. apply: (target, thisArg, args) => {
  3699. let res = undefined;
  3700. let warn = false;
  3701. let name = target._name;
  3702. if (name === 'mrg-smokescreen/Welter')
  3703. res = {
  3704. isWelter: () => true,
  3705. wrap: skipLog(`${name}.wrap`)
  3706. };
  3707. if (name === 'mrg-smokescreen/StyleSheets')
  3708. res = createSkipAllObject(name);
  3709. if (name === 'mrg-smokescreen/Honeypot')
  3710. res = {
  3711. check: (...args) => (_console.log(`${name}.check(`, ...args, ')'), new Promise(() => undefined)),
  3712. version: "-1"
  3713. }
  3714. if (name === 'advert/adman/adman') {
  3715. let features = { siteZones: {}, slots: {} };
  3716. [
  3717. 'expId', 'siteId', 'mimicEndpoint', 'mimicPartnerId', 'immediateFetchTimeout', 'delayedFetchTimeout'
  3718. ].forEach(name => void (features[name] = null));
  3719. res = {};
  3720. res.getFeatures = skipLog('advert/adman/adman.getFeatures', features);
  3721. res = createSkipAllObject(name, res);
  3722. }
  3723. if (res) {
  3724. Object.defineProperty(res, Symbol.toStringTag, {
  3725. get: () => `Skiplog object for ${name}`
  3726. });
  3727. Object.defineProperty(res, Symbol.toPrimitive, {
  3728. value: function(hint) {
  3729. if (hint === 'string')
  3730. return Object.prototype.toString.call(this);
  3731. return `[missing toPrimitive] ${name} ${hint}`;
  3732. }
  3733. });
  3734. res = new Proxy(res, missingCheck);
  3735. } else {
  3736. res = _apply(target, thisArg, args);
  3737. warn = true;
  3738. }
  3739. if (name === 'mrg-smokescreen/Utils')
  3740. res.extend = function(...args) {
  3741. let res = {
  3742. enable: false,
  3743. match: [],
  3744. links: []
  3745. };
  3746. _console.log(`${name}.extend(`, ...args, ') >>', res );
  3747. return res;
  3748. };
  3749. _console[warn?'warn':'log'](name, '(',...args,')\n>>', res);
  3750. return res;
  3751. }
  3752. };
  3753.  
  3754. let advModuleNamesStartWith = /^(mrg-(context|honeypot)|adv\/)/;
  3755. let advModuleNamesGeneric = /advert|banner|mimic|smoke/i;
  3756. let wrapAdFuncs = {
  3757. apply: (target, thisArg, args) => {
  3758. let module = args[0];
  3759. if (typeof module === 'string')
  3760. if ((advModuleNamesStartWith.test(module) ||
  3761. advModuleNamesGeneric.test(module)) &&
  3762. // fix for e.mail.ru in Fx56 and below, looks like Proxy is quirky there
  3763. !module.startsWith('patron.v2.')) {
  3764. let fun = args[args.length-1];
  3765. fun._name = module;
  3766. args[args.length-1] = new Proxy(fun, redefiner);
  3767. }
  3768. return _apply(target, thisArg, args);
  3769. }
  3770. };
  3771. let wrapDefine = def => {
  3772. if (!def)
  3773. return;
  3774. _console.log('define =', def);
  3775. def = new Proxy(def, wrapAdFuncs);
  3776. def._name = 'define';
  3777. return def;
  3778. };
  3779. let _define = wrapDefine(win.define);
  3780. Object.defineProperty(win, 'define', {
  3781. get: () => _define,
  3782. set: x => {
  3783. if (_define === x)
  3784. return true;
  3785. _define = wrapDefine(x);
  3786. return true;
  3787. }
  3788. });
  3789. }
  3790.  
  3791. let _honeyPot;
  3792. function defineDetector(mr) {
  3793. let __ = mr._ || {};
  3794. let setHoneyPot = o => {
  3795. if (!o || o === _honeyPot) return;
  3796. _console.log('[honeyPot]', o);
  3797. _honeyPot = function() {
  3798. this.check = new Proxy(() => {
  3799. __.STUCK_IN_POT = false;
  3800. return false;
  3801. }, logger);
  3802. this.check._name = 'honeyPot.check';
  3803. this.destroy = () => null;
  3804. };
  3805. };
  3806. if ('honeyPot' in mr)
  3807. setHoneyPot(mr.honeyPot);
  3808. else
  3809. Object.defineProperty(mr, 'honeyPot', {
  3810. get: () => _honeyPot,
  3811. set: setHoneyPot
  3812. });
  3813.  
  3814. __ = new Proxy(__, {
  3815. get: (t, p) => t[p],
  3816. set: (t, p, v) => {
  3817. _console.log(`mr._.${p} =`, v);
  3818. t[p] = v;
  3819. return true;
  3820. }
  3821. });
  3822. mr._ = __;
  3823. }
  3824.  
  3825. function defineAdd(mr) {
  3826. let _add;
  3827. let addWrapper = {
  3828. apply: (tgt, that, args) => {
  3829. let module = args[0];
  3830. if (typeof module === 'string' && module.startsWith('ad')) {
  3831. _console.log('Skip module:', module);
  3832. return;
  3833. }
  3834. if (typeof module === 'object' && module.name.startsWith('ad'))
  3835. _console.log('Loaded module:', module);
  3836. return logger.apply(tgt, that, args);
  3837. }
  3838. };
  3839. let setMrAdd = v => {
  3840. if (!v) return;
  3841. v._name = 'mr.add';
  3842. v = new Proxy(v, addWrapper);
  3843. _add = v;
  3844. };
  3845. if ('add' in mr)
  3846. setMrAdd(mr.add);
  3847. Object.defineProperty(mr, 'add', {
  3848. get: () => _add,
  3849. set: setMrAdd
  3850. });
  3851.  
  3852. }
  3853.  
  3854. let _mr_wrapper = vl => {
  3855. defineLocator(vl.mimic ? vl.mimic : vl);
  3856. defineDetector(vl);
  3857. defineAdd(vl);
  3858. return vl;
  3859. };
  3860. if ('mr' in win) {
  3861. _console.log('Found existing "mr" object.');
  3862. win.mr = _mr_wrapper(win.mr);
  3863. } else {
  3864. let _mr = undefined;
  3865. Object.defineProperty(win, 'mr', {
  3866. get: () => _mr,
  3867. set: vl => { _mr = _mr_wrapper(vl) },
  3868. configurable: true
  3869. });
  3870. let _defineProperty = Function.prototype.apply.bind(Object.defineProperty);
  3871. Object.defineProperty = function defineProperty(o, name, conf) {
  3872. if (name === 'mr' && o instanceof Window) {
  3873. _console.trace('Object.defineProperty(', ...arguments, ')');
  3874. conf.set(_mr_wrapper(conf.get()));
  3875. }
  3876. if ((name === 'honeyPot' || name === 'add') && _mr === o && conf.set)
  3877. return;
  3878. return _defineProperty(this, arguments);
  3879. };
  3880. }
  3881. }, nullTools, selectiveCookies, abortExecutionModule)
  3882. };
  3883.  
  3884. scripts['oms.matchat.online'] = () => scriptLander(() => {
  3885. let _rmpGlobals = undefined;
  3886. Object.defineProperty(win, 'rmpGlobals', {
  3887. get: () => _rmpGlobals,
  3888. set: x => {
  3889. if (x === _rmpGlobals)
  3890. return true;
  3891. _rmpGlobals = new Proxy(x, {
  3892. get: (obj, name) => {
  3893. if (name === 'adBlockerDetected')
  3894. return false;
  3895. return obj[name];
  3896. },
  3897. set: (obj, name, val) => {
  3898. if (name === 'adBlockerDetected')
  3899. _console.trace('rmpGlobals.adBlockerDetected = %o', val)
  3900. else
  3901. obj[name] = val;
  3902. return true;
  3903. }
  3904. });
  3905. }
  3906. });
  3907. });
  3908.  
  3909. scripts['megogo.net'] = {
  3910. now: () => {
  3911. nt.define('adBlock', false);
  3912. nt.define('showAdBlockMessage', nt.func(null));
  3913. }
  3914. };
  3915.  
  3916. scripts['metabomb.net'] = {
  3917. other: 'eurogamer.net, eurogamer.cz, eurogamer.de, eurogamer.es, eurogamer.it' +
  3918. 'eurogamer.nl, eurogamer.pl, eurogamer.pt, usgamer.net',
  3919. now: () => scriptLander(() => {
  3920. abortExecution(onAccess.InlineScript, '_sp_');
  3921. selectiveCookies('sp');
  3922. }, selectiveCookies, abortExecutionModule)
  3923. };
  3924.  
  3925. scripts['n-torrents.org'] = () => scriptLander(() => {
  3926. let _$ = undefined;
  3927. Object.defineProperty(win, '$', {
  3928. get: () => _$,
  3929. set: vl => {
  3930. _$ = vl;
  3931. if (!vl.fn)
  3932. return true;
  3933. let _videoPopup = vl.fn.videoPopup;
  3934. Object.defineProperty(vl.fn, 'videoPopup', {
  3935. get: () => _videoPopup,
  3936. set: vl => {
  3937. if (vl === _videoPopup)
  3938. return true;
  3939. _videoPopup = new Proxy(vl, {
  3940. apply: (fun, obj, args) => {
  3941. let opts = args[0];
  3942. if (opts) {
  3943. opts.adv = '';
  3944. opts.duration = 0;
  3945. }
  3946. return Reflect.apply(fun, obj, args);
  3947. }
  3948. });
  3949. return true;
  3950. }
  3951. });
  3952. return true
  3953. }
  3954. });
  3955. });
  3956.  
  3957. scripts['naruto-base.su'] = () => gardener('div[id^="entryID"],.block', /href="http.*?target="_blank"/i);
  3958.  
  3959. scripts['newdeaf-online.net'] = {
  3960. dom: () => {
  3961. let adNodes = _document.querySelectorAll('.ads');
  3962. if (!adNodes)
  3963. return;
  3964. let getter = x => {
  3965. let val = x;
  3966. return () => (_console.trace('read .ads', name, val), val);
  3967. };
  3968. let setter = x => _console.trace('skip write .ads', name, x);
  3969. for (let adNode of adNodes)
  3970. for (let name of ['innerHTML'])
  3971. Object.defineProperty(adNode, name, {
  3972. get: getter(ads[name]),
  3973. set: setter
  3974. });
  3975. }
  3976. };
  3977.  
  3978. scripts['overclockers.ru'] = {
  3979. dom: () => scriptLander(() => {
  3980. let killed = () => _console.warn('Anti-Adblock killed.');
  3981. if ('$' in win)
  3982. win.$ = new Proxy($, {
  3983. apply: (tgt, that, args) => {
  3984. let res = tgt.apply(that, args);
  3985. if (res[0] && res[0] === _document.body) {
  3986. res.html = killed;
  3987. res.empty = killed;
  3988. }
  3989. return res;
  3990. }
  3991. });
  3992. })
  3993. };
  3994. scripts['forums.overclockers.ru'] = {
  3995. now: () => {
  3996. createStyle('.needblock {position: fixed; left: -10000px}');
  3997. Object.defineProperty(win, 'adblck', {
  3998. get: () => 'no',
  3999. set: () => undefined,
  4000. enumerable: true
  4001. });
  4002. }
  4003. };
  4004.  
  4005. scripts['pb.wtf'] = {
  4006. other: 'piratbit.org, piratbit.pw, piratbit.top',
  4007. dom: () => {
  4008. const remove = node => node && node.parentNode && (_console.log('removed', node), node.parentNode.removeChild(node));
  4009. const isAdLink = el => location.hostname === el.hostname && /^\/(\w{3}|exit|out)\/[\w=/]{20,}$/.test(el.pathname);
  4010. // line above topic content and images in the slider in the header
  4011. for (let el of _document.querySelectorAll('.releas-navbar div a, #page_contents a')) if (isAdLink(el))
  4012. remove(el.closest('tr[class]:not(.top_line):not(.active), .row2[id^="post_"]') || el.closest('div[style]:not(.row1):not(.btn-group)'));
  4013. }
  4014. };
  4015.  
  4016. scripts['pikabu.ru'] = () => gardener('.story', /story__author[^>]+>ads</i, {root: '.inner_wrap', observe: true});
  4017.  
  4018. scripts['peka2.tv'] = () => {
  4019. let bodyClass = 'body--branding';
  4020. let checkNode = node => {
  4021. for (let className of node.classList)
  4022. if (className.includes('banner') || className === bodyClass) {
  4023. _removeAttribute(node, 'style');
  4024. node.classList.remove(className);
  4025. for (let attr of Array.from(node.attributes))
  4026. if (attr.name.startsWith('advert'))
  4027. _removeAttribute(node, attr.name);
  4028. }
  4029. };
  4030. (new MutationObserver(ms => {
  4031. let m, node;
  4032. for (m of ms) for (node of m.addedNodes)
  4033. if (node instanceof HTMLElement)
  4034. checkNode(node);
  4035. })).observe(_de, {childList: true, subtree: true});
  4036. (new MutationObserver(ms => {
  4037. for (let m of ms)
  4038. checkNode(m.target);
  4039. })).observe(_de, {attributes: true, subtree: true, attributeFilter: ['class']});
  4040. };
  4041.  
  4042. scripts['qrz.ru'] = {
  4043. now: () => {
  4044. nt.define('ab', false);
  4045. nt.define('tryMessage', nt.func(null));
  4046. }
  4047. };
  4048.  
  4049. scripts['razlozhi.ru'] = {
  4050. now: () => {
  4051. nt.define('cadb', false);
  4052. for (let func of ['createShadowRoot', 'attachShadow'])
  4053. if (func in _Element)
  4054. _Element[func] = function(){
  4055. return this.cloneNode();
  4056. };
  4057. }
  4058. };
  4059.  
  4060. scripts['rbc.ru'] = {
  4061. other: 'autonews.ru, rbcplus.ru, sportrbc.ru',
  4062. now: () => {
  4063. scriptLander(() => selectiveCookies('adb_on'), selectiveCookies);
  4064. let _RA = undefined;
  4065. let setArgs = {
  4066. 'showBanners': true,
  4067. 'showAds': true,
  4068. 'banners.staticPath': '',
  4069. 'paywall.staticPath': '',
  4070. 'banners.dfp.config': [],
  4071. 'banners.dfp.pageTargeting': () => null,
  4072. };
  4073. Object.defineProperty(win, 'RA', {
  4074. get: () => _RA,
  4075. set: vl => {
  4076. _console.log('RA =', vl);
  4077. if ('repo' in vl) {
  4078. _console.log('RA.repo =', vl.repo);
  4079. vl.repo = new Proxy(vl.repo, {
  4080. set: (o, name, val) => {
  4081. if (name === 'banner') {
  4082. _console.log(`RA.repo.${name} =`, val);
  4083. val = new Proxy(val, {
  4084. get: (o, name) => {
  4085. let res = o[name];
  4086. if (typeof o[name] === 'function') {
  4087. res = () => undefined;
  4088. if (name === 'getService')
  4089. res = service => {
  4090. if (service === 'dfp')
  4091. return {
  4092. getPlaces: () => undefined,
  4093. createPlaceholder: () => undefined
  4094. }
  4095. return undefined;
  4096. }
  4097. res.toString = o[name].toString.bind(o[name]);
  4098. }
  4099. if (name === 'isInited')
  4100. res = true;
  4101. _console.trace(`get RA.repo.banner.${name} %o`, res);
  4102. return res;
  4103. }
  4104. });
  4105. }
  4106. o[name] = val;
  4107. return true;
  4108. }
  4109. });
  4110. } else
  4111. _console.log('Unable to locate RA.repo');
  4112. _RA = new Proxy(vl, {
  4113. set: (o, name, val) => {
  4114. if (name === 'config') {
  4115. _console.log('RA.config =', val);
  4116. if ('set' in val) {
  4117. val.set = new Proxy(val.set, {
  4118. apply: (set, that, args) => {
  4119. let name = args[0];
  4120. if (name in setArgs)
  4121. args[1] = setArgs[name];
  4122. if (name in setArgs || name === 'checkad')
  4123. _console.log('RA.config.set(', ...args, ')');
  4124. return Reflect.apply(set, that, args);
  4125. }
  4126. });
  4127. val.set('showAds', true); // pretend ads already were shown
  4128. }
  4129. }
  4130. o[name] = val;
  4131. return true;
  4132. }
  4133. });
  4134. }
  4135. });
  4136. Object.defineProperty(win, 'bannersConfig', {
  4137. get: () => [], set: () => null
  4138. });
  4139. // pretend there is a paywall landing on screen already
  4140. let pwl = _document.createElement('div');
  4141. pwl.style.display = 'none';
  4142. pwl.className = 'js-paywall-landing';
  4143. _document.documentElement.appendChild(pwl);
  4144. // detect and skip execution of one of the ABP detectors
  4145. let _setTimeout = Function.prototype.apply.bind(win.setTimeout);
  4146. let _toString = Function.prototype.call.bind(Function.prototype.toString);
  4147. win.setTimeout = function setTimeout() {
  4148. if (typeof arguments[0] === 'function') {
  4149. let fts = _toString(arguments[0]);
  4150. if (/\.length\s*>\s*0\s*&&/.test(fts) && /:hidden/.test(fts)) {
  4151. _console.log('Skipped setTimout(', fts, arguments[1], ')');
  4152. return;
  4153. }
  4154. }
  4155. return _setTimeout(this, arguments);
  4156. };
  4157. // hide banner placeholders
  4158. createStyle('[data-banner-id], .banner__container, .banners__yandex__article { display: none !important }');
  4159. },
  4160. dom: () => {
  4161. // hide sticky banner place at the top of the page
  4162. for (let itm of _document.querySelectorAll('.l-sticky'))
  4163. if (itm.querySelector('.banner__container__link'))
  4164. itm.style.display = 'none';
  4165. }
  4166. };
  4167.  
  4168. scripts['rp5.ru'] = {
  4169. other: 'rp5.by, rp5.co.uk, rp5.kz, rp5.lv, rp5.md, rp5.ua',
  4170. now: () => {
  4171. Object.defineProperty(win, 'sContentBottom', {
  4172. get: () => '',
  4173. set: () => true
  4174. });
  4175. // skip timeout check for blocked requests
  4176. let _setTimeout = Function.prototype.apply.bind(win.setTimeout);
  4177. let _toString = Function.prototype.apply.bind(Function.prototype.toString);
  4178. win.setTimeout = function(...args) {
  4179. let str = (typeof args[0] === 'string' ? args[0] : _toString(args[0]));
  4180. if (str.includes('xvb')) {
  4181. _console.log('Blocked setTimeout for:', str);
  4182. return;
  4183. }
  4184. return _setTimeout(this, args);
  4185. };
  4186. },
  4187. dom: () => {
  4188. let node = selectNodeByTextContent('Разместить текстовое объявление', { root: _de.querySelector('#content-wrapper'), shallow: true });
  4189. if (node)
  4190. node.style.display = 'none';
  4191. }
  4192. };
  4193.  
  4194. scripts['rutube.ru'] = () => scriptLander(() => {
  4195. let _parse = JSON.parse;
  4196. let _skip_enabled = false;
  4197. JSON.parse = (...args) => {
  4198. let res = _parse(...args),
  4199. log = false;
  4200. if (!res)
  4201. return res;
  4202. // parse player configuration
  4203. if ('appearance' in res || 'video_balancer' in res) {
  4204. log = true;
  4205. if (res.appearance) {
  4206. if ('forbid_seek' in res.appearance && res.appearance.forbid_seek)
  4207. res.appearance.forbid_seek = false;
  4208. if ('forbid_timeline_preview' in res.appearance && res.appearance.forbid_timeline_preview)
  4209. res.appearance.forbid_timeline_preview = false;
  4210. }
  4211. _skip_enabled = !!res.remove_unseekable_blocks;
  4212. //res.advert = [];
  4213. delete res.advert;
  4214. //for (let limit of res.limits)
  4215. // limit.limit = 0;
  4216. delete res.limits;
  4217. //res.yast = null;
  4218. //res.yast_live_online = null;
  4219. delete res.yast;
  4220. delete res.yast_live_online;
  4221. Object.defineProperty(res, 'stat', {
  4222. get: () => [],
  4223. set: () => true,
  4224. enumerable: true
  4225. });
  4226. }
  4227.  
  4228. // parse video configuration
  4229. if ('video_url' in res) {
  4230. log = true;
  4231. if (res.cuepoints && !_skip_enabled)
  4232. for (let point of res.cuepoints) {
  4233. point.is_pause = false;
  4234. point.show_navigation = true;
  4235. point.forbid_seek = false;
  4236. }
  4237. }
  4238.  
  4239. if (log)
  4240. _console.log('[rutube]', res);
  4241. return res;
  4242. };
  4243. });
  4244.  
  4245. scripts['simpsonsua.com.ua'] = {
  4246. other: 'simpsonsua.tv',
  4247. now: () => scriptLander(() => {
  4248. let _addEventListener = _Document.addEventListener;
  4249. _document.addEventListener = function(event, callback) {
  4250. if (event === 'DOMContentLoaded' && callback.toString().includes('show_warning'))
  4251. return;
  4252. return _addEventListener.apply(this, arguments);
  4253. };
  4254. nt.define('need_warning', 0);
  4255. nt.define('onYouTubeIframeAPIReady', nt.func(null));
  4256. }, nullTools)
  4257. };
  4258.  
  4259. scripts['smotret-anime-365.ru'] = () => scriptLander(() => {
  4260. deepWrapAPI(root => {
  4261. let _call = root.Function.prototype.call;
  4262. let _pause = _call.bind(root.Audio.prototype.pause);
  4263. let _addEventListener = _call.bind(root.Element.prototype.addEventListener);
  4264. let stopper = e => _pause(e.target);
  4265. let _construct = root.Reflect.construct;
  4266. root.Audio = new Proxy(root.Audio, {
  4267. construct: (audio, args) => {
  4268. let res = _construct(audio, args);
  4269. _addEventListener(res, 'play', stopper, true);
  4270. return res;
  4271. }
  4272. });
  4273. let _apply = root.Reflect.apply;
  4274. let _tagName_get = _call.bind(Object.getOwnPropertyDescriptor(_Element, 'tagName').get);
  4275. root.Document.prototype.createElement = new Proxy(root.Document.prototype.createElement, {
  4276. apply: (fun, that, args) => {
  4277. let res = _apply(fun, that, args);
  4278. if (_tagName_get(res) === 'AUDIO')
  4279. _addEventListener(res, 'play', stopper, true);
  4280. return res;
  4281. }
  4282. });
  4283. });
  4284. }, deepWrapAPI);
  4285.  
  4286. scripts['spaces.ru'] = () => {
  4287. gardener('div:not(.f-c_fll) > a[href*="spaces.ru/?Cl="]', /./, { parent: 'div' });
  4288. gardener('.js-banner_rotator', /./, { parent: '.widgets-group' });
  4289. };
  4290.  
  4291. scripts['spam-club.blogspot.co.uk'] = () => {
  4292. let _clientHeight = Object.getOwnPropertyDescriptor(_Element, 'clientHeight'),
  4293. _clientWidth = Object.getOwnPropertyDescriptor(_Element, 'clientWidth');
  4294. let wrapGetter = (getter) => {
  4295. let _getter = getter;
  4296. return function() {
  4297. let _size = _getter.apply(this, arguments);
  4298. return _size ? _size : 1;
  4299. };
  4300. };
  4301. _clientHeight.get = wrapGetter(_clientHeight.get);
  4302. _clientWidth.get = wrapGetter(_clientWidth.get);
  4303. Object.defineProperty(_Element, 'clientHeight', _clientHeight);
  4304. Object.defineProperty(_Element, 'clientWidth', _clientWidth);
  4305. let _onload = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onload'),
  4306. _set_onload = _onload.set;
  4307. _onload.set = function() {
  4308. if (this instanceof HTMLImageElement)
  4309. return true;
  4310. _set_onload.apply(this, arguments);
  4311. };
  4312. Object.defineProperty(HTMLElement.prototype, 'onload', _onload);
  4313. };
  4314.  
  4315. scripts['sport-express.ru'] = () => gardener('.js-relap__item',/>Реклама\s+<\//, {root:'.container', observe: true});
  4316.  
  4317. scripts['sports.ru'] = {
  4318. other: 'tribuna.com',
  4319. now: () => {
  4320. // extra functionality: shows/hides panel at the top depending on scroll direction
  4321. createStyle([
  4322. '.user-panel__fixed { transition: top 0.2s ease-in-out!important; }',
  4323. '.popup__overlay.feedback { display: none!important }',
  4324. '.user-panel-up { top: -40px!important }',
  4325. '#branding-layout { margin-top: 100px!important }'
  4326. ], {id: 'fixes'}, false);
  4327. scriptLander(() => {
  4328. yandexRavenStub();
  4329. webpackJsonpFilter(/AdBlockDetector|addBranding|loadPlista/);
  4330. }, nullTools, yandexRavenStub, webpackJsonpFilter);
  4331. },
  4332. dom: () => {
  4333. (function lookForPanel() {
  4334. let panel = _document.querySelector('.user-panel__fixed');
  4335. if (!panel)
  4336. setTimeout(lookForPanel, 100);
  4337. else
  4338. window.addEventListener(
  4339. 'wheel', function(e) {
  4340. if (e.deltaY > 0 && !panel.classList.contains('user-panel-up'))
  4341. panel.classList.add('user-panel-up');
  4342. else if (e.deltaY < 0 && panel.classList.contains('user-panel-up'))
  4343. panel.classList.remove('user-panel-up');
  4344. }, false
  4345. );
  4346. })();
  4347. }
  4348. };
  4349. scripts['stealthz.ru'] = {
  4350. dom: () => {
  4351. // skip timeout
  4352. let $ = _document.querySelector.bind(_document);
  4353. let [timer_1, timer_2] = [$('#timer_1'), $('#timer_2')];
  4354. if (!timer_1 || !timer_2)
  4355. return;
  4356. timer_1.style.display = 'none';
  4357. timer_2.style.display = 'block';
  4358. }
  4359. };
  4360.  
  4361. scripts['video.khl.ru'] = () => {
  4362. let props = new Set(['detectBlockers', 'detectBlockersByLink', 'detectBlockersByElement']);
  4363. win.Object.defineProperty = new Proxy(win.Object.defineProperty, {
  4364. apply (def, that, args) {
  4365. if (props.has(args[1])) {
  4366. args[2] = {
  4367. key: args[1],
  4368. value: () => _console.log(`Skipped ${args[1]} call.`)
  4369. };
  4370. _console.log(`Replaced method ${args[1]}.`);
  4371. }
  4372. return Reflect.apply(def, that, args);
  4373. }
  4374. });
  4375. };
  4376.  
  4377. scripts['xatab-repack.net'] = {
  4378. other: 'rg-mechanics.org',
  4379. now: () => abortExecution(onAccess.Set, 'blocked')
  4380. };
  4381.  
  4382. scripts['xittv.net'] = () => scriptLander(() => {
  4383. let logNames = ['setup', 'trigger', 'on', 'off', 'onReady', 'onError', 'getConfig', 'addPlugin', 'getAdBlock'];
  4384. let skipEvents = ['adComplete', 'adSkipped', 'adBlock', 'adRequest', 'adMeta', 'adImpression', 'adError', 'adTime', 'adStarted', 'adClick'];
  4385. let _jwplayer = undefined;
  4386. Object.defineProperty(win, 'jwplayer', {
  4387. get: () => _jwplayer,
  4388. set: x => {
  4389. _jwplayer = new Proxy(x, {
  4390. apply: (fun, that, args) => {
  4391. let res = fun.apply(that, args);
  4392. res = new Proxy(res, {
  4393. get: (obj, name) => {
  4394. if (logNames.includes(name) && obj[name] instanceof Function)
  4395. return new Proxy(obj[name], {
  4396. apply: (fun, that, args) => {
  4397. if (name === 'setup') {
  4398. let o = args[0];
  4399. if (o)
  4400. delete o.advertising;
  4401. }
  4402. if (name === 'on' || name === 'trigger') {
  4403. let events = typeof args[0] === 'string' ? args[0].split(" ") : null;
  4404. if (events.length === 1 && skipEvents.includes(events[0]))
  4405. return res;
  4406. if (events.length > 1) {
  4407. let names = [];
  4408. for (let event of events)
  4409. if (!skipEvents.includes(event))
  4410. names.push(event);
  4411. if (names.length > 0)
  4412. args[0] = names.join(" ");
  4413. else
  4414. return res;
  4415. }
  4416. }
  4417. let subres = fun.apply(that, args);
  4418. _console.trace(`jwplayer().${name}(`, ...args, `) >>`, res);
  4419. return subres;
  4420. }
  4421. });
  4422. return obj[name];
  4423. }
  4424. });
  4425. return res;
  4426. }
  4427. });
  4428. _console.log('jwplayer =', x);
  4429. }
  4430. });
  4431. });
  4432.  
  4433. scripts['yap.ru'] = {
  4434. other: 'yaplakal.com',
  4435. now: () => {
  4436. gardener('form > table[id^="p_row_"]:nth-of-type(2)', /member1438|Administration/);
  4437. gardener('.icon-comments', /member1438|Administration|\/go\/\?http/, {parent:'tr', siblings:-2});
  4438. }
  4439. };
  4440.  
  4441. scripts['yapx.ru'] = () => scriptLander(() => {
  4442. selectiveCookies('adblock_state|adblock_views');
  4443. nt.define('blockAdBlock', {
  4444. on: nt.func(nt.proxy({}, 'blockAdBlock.on', null), 'blockAdBlock.on'),
  4445. check: nt.func(null, 'blockAdBlock.check')
  4446. });
  4447. }, selectiveCookies, nullTools);
  4448.  
  4449. scripts['znanija.com'] = () => scriptLander(() => {
  4450. abortExecution(onAccess.Set, 'getAdBlockType');
  4451. }, abortExecutionModule);
  4452.  
  4453. scripts['rambler.ru'] = {
  4454. other: 'championat.com, eda.ru, gazeta.ru, lenta.ru, media.eagleplatform.com, passion.ru, quto.ru, rns.online, wmj.ru',
  4455. now: () => {
  4456. scriptLander(() => {
  4457. selectiveCookies('detect_count');
  4458. // Prevent autoplay
  4459. if (!('EaglePlayer' in win)) {
  4460. let _EaglePlayer = undefined;
  4461. Object.defineProperty(win, 'EaglePlayer', {
  4462. enumerable: true,
  4463. get: () => _EaglePlayer,
  4464. set: x => {
  4465. if (x === _EaglePlayer)
  4466. return true;
  4467. _EaglePlayer = new Proxy(x, {
  4468. construct: (targ, args) => {
  4469. let player = new targ(...args);
  4470. if (!player.options) {
  4471. _console.log('EaglePlayer: no options', EaglePlayer);
  4472. return player;
  4473. }
  4474. Object.defineProperty(player.options, 'autoplay', {
  4475. get: () => false,
  4476. set: () => true
  4477. });
  4478. Object.defineProperty(player.options, 'scroll', {
  4479. get: () => false,
  4480. set: () => true
  4481. });
  4482. return player;
  4483. }
  4484. });
  4485. }
  4486. });
  4487. let _setAttribute = Function.prototype.apply.bind(_Element.setAttribute);
  4488. let isAutoplay = /^autoplay$/i;
  4489. _Element.setAttribute = function setAttribute(name) {
  4490. if (!this._stopped && isAutoplay.test(name)) {
  4491. _console.log('Prevented assigning autoplay attribute.');
  4492. return null;
  4493. }
  4494. return _setAttribute(this, arguments);
  4495. };
  4496. } else {
  4497. _console.log('EaglePlayer function already exists.');
  4498. if (inIFrame) {
  4499. let _setAttribute = Function.prototype.apply.bind(_Element.setAttribute);
  4500. let isAutoplay = /^autoplay$/i;
  4501. _Element.setAttribute = function setAttribute(name) {
  4502. if (!this._stopped && isAutoplay.test(name)) {
  4503. _console.log('Prevented assigning autoplay attribute.');
  4504. this._stopped = true;
  4505. this.play = () => {
  4506. _console.log('Prevented attempt to force-start playback.');
  4507. delete this.play;
  4508. };
  4509. return null;
  4510. }
  4511. return _setAttribute(this, arguments);
  4512. };
  4513. }
  4514. }
  4515. if (location.hostname.endsWith('.media.eagleplatform.com'))
  4516. return;
  4517. // Wrapper for adv loader settings in QW50aS1BZEJsb2Nr['7t7hystz']
  4518. let _contexts = new WeakMap();
  4519. Object.defineProperty(Object.prototype, 'Settings', {
  4520. set: function(val) {
  4521. if (typeof val === 'object' && 'Transports' in val && 'Urls' in val)
  4522. val.Urls = [];
  4523. _contexts.set(this, val);
  4524. },
  4525. get: function() { return _contexts.get(this); }
  4526. });
  4527. // disable some logging
  4528. yandexRavenStub();
  4529. // prevent ads from loading
  4530. abortExecution(onAccess.Get, 'g_GazetaNoExchange');
  4531.  
  4532. let blockPatterns = /\[[a-z]{1,4}\("0x[\da-f]+"\)\]|\.(rnet\.plus|24smi\.net|infox\.sg|lentainform\.com)\//i;
  4533. let _toString = Function.prototype.call.bind(Function.prototype.toString);
  4534. let _setTimeout = Function.prototype.call.bind(win.setTimeout);
  4535. win.setTimeout = function setTimeout(f, sleep) {
  4536. let str = (typeof f === 'function' ? _toString(f) : ''),
  4537. detected = blockPatterns.test(str);
  4538. if (!detected && f) {
  4539. try {
  4540. str = f.toString();
  4541. } catch(ignore) {};
  4542. if (str)
  4543. detected = blockPatterns.test(str);
  4544. }
  4545. if (detected) {
  4546. _console.trace(`Stopped setTimeout for: ${str.slice(0,100)}\u2026`);
  4547. return null;
  4548. };
  4549. return _setTimeout(this, f, sleep);
  4550. };
  4551. }, nullTools, yandexRavenStub, selectiveCookies, abortExecutionModule)
  4552. },
  4553. dom: () => {
  4554. // remove utm_ form links
  4555. let parser = _document.createElement('a');
  4556. _document.addEventListener('mousedown', (e) => {
  4557. let t = e.target;
  4558. if (!t.href)
  4559. t = t.closest('A');
  4560. if (t && t.href) {
  4561. parser.href = t.href;
  4562. let remove = [];
  4563. let params = parser.search.slice(1).split('&').filter(name => {
  4564. if (name.startsWith('utm_')) {
  4565. remove.push(name);
  4566. return false;
  4567. }
  4568. return true;
  4569. });
  4570. if (remove.length)
  4571. _console.log('Removed parameters from link:', ...remove);
  4572. if (params.length)
  4573. parser.search = `?${params.join('&')}`;
  4574. else
  4575. parser.search = '';
  4576. t.href = parser.href;
  4577. }
  4578. }, false);
  4579. }
  4580. };
  4581.  
  4582. scripts['reactor.cc'] = {
  4583. other: 'joyreactor.cc, pornreactor.cc',
  4584. now: () => {
  4585. scriptLander(() => {
  4586. selectiveEval();
  4587. win.open = function(){
  4588. throw new ReferenceError('Redirect prevention.');
  4589. };
  4590. nt.define('Worker', function(){});
  4591. nt.define('JRCH', win.CoinHive);
  4592. }, nullTools, selectiveEval);
  4593. },
  4594. click: function(e) {
  4595. let node = e.target;
  4596. if (node.nodeType === _Node.ELEMENT_NODE &&
  4597. node.style.position === 'absolute' &&
  4598. node.style.zIndex > 0)
  4599. node.parentNode.removeChild(node);
  4600. },
  4601. dom: function() {
  4602. let tid = undefined;
  4603. function probe() {
  4604. let node = selectNodeByTextContent('блокировщик рекламы');
  4605. if (!node) return;
  4606. while (node.parentNode.offsetHeight < 750 && node !== _document.body)
  4607. node = node.parentNode;
  4608. _setAttribute(node, 'style', 'background:none!important');
  4609. // stop observer
  4610. if (!tid) tid = setTimeout(() => this.disconnect(), 1000);
  4611. }
  4612. (new MutationObserver(probe))
  4613. .observe(_document, { childList:true, subtree:true });
  4614. }
  4615. };
  4616.  
  4617. scripts['auto.ru'] = () => {
  4618. let words = /Реклама|Яндекс.Директ|yandex_ad_/;
  4619. let userAdsListAds = (
  4620. '.listing-list > .listing-item,'+
  4621. '.listing-item_type_fixed.listing-item'
  4622. );
  4623. let catalogAds = (
  4624. 'div[class*="layout_catalog-inline"],'+
  4625. 'div[class$="layout_horizontal"]'
  4626. );
  4627. let otherAds = (
  4628. '.advt_auto,'+
  4629. '.sidebar-block,'+
  4630. '.pager-listing + div[class],'+
  4631. '.card > div[class][style],'+
  4632. '.sidebar > div[class],'+
  4633. '.main-page__section + div[class],'+
  4634. '.listing > tbody'
  4635. );
  4636. gardener(userAdsListAds, words, {root:'.listing-wrap', observe:true});
  4637. gardener(catalogAds, words, {root:'.catalog__page,.content__wrapper', observe:true});
  4638. gardener(otherAds, words);
  4639. };
  4640.  
  4641. scripts['rsload.net'] = {
  4642. load: () => {
  4643. let dis = _document.querySelector('label[class*="cb-disable"]');
  4644. if (dis)
  4645. dis.click();
  4646. },
  4647. click: e => {
  4648. let t = e.target;
  4649. if (t && t.href && (/:\/\/\d+\.\d+\.\d+\.\d+\//.test(t.href)))
  4650. t.href = t.href.replace('://','://rsload.net:rsload.net@');
  4651. }
  4652. };
  4653.  
  4654. // add alternative domain names if present and wrap functions into objects
  4655. for (let name in scripts) {
  4656. if (scripts[name] instanceof Function)
  4657. scripts[name] = { now: scripts[name] };
  4658. for (let domain of (scripts[name].other && scripts[name].other.split(/,\s*/) || [])) {
  4659. if (domain in scripts)
  4660. _console.log('Error in scripts list. Script for', name, 'replaced script for', domain);
  4661. scripts[domain] = scripts[name];
  4662. }
  4663. delete scripts[name].other;
  4664. }
  4665. // look for current domain in the list and run appropriate code
  4666. let domain = _document.domain;
  4667. while (domain.includes('.')) {
  4668. if (domain in scripts) for (let when in scripts[domain])
  4669. switch(when) {
  4670. case 'now':
  4671. scripts[domain][when]();
  4672. break;
  4673. case 'dom':
  4674. _document.addEventListener('DOMContentLoaded', scripts[domain][when], false);
  4675. break;
  4676. default:
  4677. _document.addEventListener (when, scripts[domain][when], false);
  4678. }
  4679. domain = domain.slice(domain.indexOf('.') + 1);
  4680. }
  4681.  
  4682. // Batch script lander
  4683. if (!skipLander)
  4684. landScript(batchLand, batchPrepend);
  4685.  
  4686. { // JS Fixes Tools Menu
  4687. // Debug function, lists all unusual window properties
  4688. let _toString = Function.prototype.call.bind(Function.prototype.toString);
  4689. let isNativeFunction = new RegExp (`^[^{]*\\{[\\s\\r\\n]*\\[native\\scode\\][\\s\\r\\n]*\\}$`);
  4690. function getStrangeObjectsList() {
  4691. _console.group('Window strangers list');
  4692. let _skip = 'frames/self/window/webkitStorageInfo'.split('/');
  4693. for (let n of Object.getOwnPropertyNames(win))
  4694. try {
  4695. let val = win[n];
  4696. if (val && !_skip.includes(n) && (win !== window && val !== window[n] || win === window) &&
  4697. (!(val instanceof Function) || val instanceof Function && !isNativeFunction.test(_toString(val))))
  4698. _console.log(`${n} =`, val);
  4699. } catch (e) {
  4700. _console.log(n, 'returns error on read', e);
  4701. }
  4702. _console.groupEnd('Window strangers list');
  4703. }
  4704.  
  4705. let openOptions = function() {
  4706. let ovl = _createElement('div'),
  4707. inner = _createElement('div');
  4708. ovl.style = (
  4709. 'position: fixed;'+
  4710. 'top:0; left:0;'+
  4711. 'bottom: 0; right: 0;'+
  4712. 'background: rgba(0,0,0,0.85);'+
  4713. 'z-index: 2147483647;'+
  4714. 'padding: 5em'
  4715. );
  4716. inner.style = (
  4717. 'background: whitesmoke;'+
  4718. 'font-size: 10pt;'+
  4719. 'color: black;'+
  4720. 'padding: 1em'
  4721. );
  4722. inner.textContent = 'JS Fixes Tools';
  4723. inner.appendChild(_createElement('br'));
  4724. inner.appendChild(_createElement('br'));
  4725. ovl.addEventListener(
  4726. 'click', function(e) {
  4727. if (e.target === ovl) {
  4728. ovl.parentNode.removeChild(ovl);
  4729. e.preventDefault();
  4730. }
  4731. e.stopPropagation();
  4732. }, false
  4733. );
  4734.  
  4735. let sObjBtn = _createElement('button');
  4736. sObjBtn.onclick = getStrangeObjectsList;
  4737. sObjBtn.textContent = 'Print (in console) list of unusual window properties';
  4738. inner.appendChild(_createElement('br'));
  4739. inner.appendChild(sObjBtn);
  4740.  
  4741. _document.body.appendChild(ovl);
  4742. ovl.appendChild(inner);
  4743. };
  4744.  
  4745. // monitor keys pressed for Ctrl+Alt+Shift+J > s > f code
  4746. let opPos = 0, opKey = ['KeyJ','KeyS','KeyF'];
  4747. _document.addEventListener(
  4748. 'keydown', function(e) {
  4749. if ((e.code === opKey[opPos] || e.location) &&
  4750. (!!opPos || e.altKey && e.ctrlKey && e.shiftKey)) {
  4751. opPos += e.location ? 0 : 1;
  4752. e.stopPropagation();
  4753. e.preventDefault();
  4754. } else
  4755. opPos = 0;
  4756. if (opPos === opKey.length) {
  4757. opPos = 0;
  4758. openOptions();
  4759. }
  4760. }, false
  4761. );
  4762. }
  4763. })();