RU AdList JS Fixes

try to take over the world!

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

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