RU AdList JS Fixes

try to take over the world!

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

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