RU AdList JS Fixes

try to take over the world!

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

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