RU AdList JS Fixes

try to take over the world!

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

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