RU AdList JS Fixes

try to take over the world!

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

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