RU AdList JS Fixes

try to take over the world!

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

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

QingJ © 2025

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