RU AdList JS Fixes

try to take over the world!

目前為 2020-01-09 提交的版本,檢視 最新版本

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址