Greasy Fork 还支持 简体中文。

RU AdList JS Fixes

try to take over the world!

目前為 2019-12-08 提交的版本,檢視 最新版本

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