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