RU AdList JS Fixes

try to take over the world!

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

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