RU AdList JS Fixes

try to take over the world!

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

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