RU AdList JS Fixes

try to take over the world!

当前为 2019-10-27 提交的版本,查看 最新版本

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