RU AdList JS Fixes

try to take over the world!

目前为 2019-06-27 提交的版本。查看 最新版本

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