RU AdList JS Fixes

try to take over the world!

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

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