RU AdList JS Fixes

try to take over the world!

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

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