RU AdList JS Fixes

try to take over the world!

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

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