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