RU AdList JS Fixes

try to take over the world!

当前为 2019-12-13 提交的版本,查看 最新版本

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

QingJ © 2025

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