RU AdList JS Fixes

try to take over the world!

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

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