RU AdList JS Fixes

try to take over the world!

当前为 2019-08-05 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name RU AdList JS Fixes
  3. // @namespace ruadlist_js_fixes
  4. // @version 20190805.0
  5. // @description try to take over the world!
  6. // @author lainverse & dimisa
  7. // @supportURL https://greasyfork.org/en/scripts/19993-ru-adlist-js-fixes/feedback
  8. // @match *://*/*
  9. // @exclude *://auth.wi-fi.ru/*
  10. // @exclude *://*.alfabank.ru/*
  11. // @exclude *://alfabank.ru/*
  12. // @exclude *://*.unicreditbanking.net/*
  13. // @exclude *://unicreditbanking.net/*
  14. // @exclude *://*.telegram.org/*
  15. // @exclude *://telegram.org/*
  16. // @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. // Based on https://greasyfork.org/en/scripts/21937-moonwalk-hdgo-kodik-fix v0.8
  1275. PlayerFix: {
  1276. let log = name => _console.log(`Player FIX: Detected ${name} player in ${location.href}`);
  1277. function removeVast (data) {
  1278. if (data && typeof data === 'object') {
  1279. _console.log('Player configuration:', data);
  1280. if (data.advert_script && data.advert_script !== '') {
  1281. _console.log('Set data.advert_script to empty string.');
  1282. data.advert_script = '';
  1283. }
  1284. let keys = Object.getOwnPropertyNames(data);
  1285. let isVast = name => /vast|clickunder/.test(name);
  1286. if (!keys.some(isVast))
  1287. return data;
  1288. for (let key of keys)
  1289. if (typeof data[key] === 'object' && key !== 'links') {
  1290. _console.log(`Removed data.${key}`, data[key]);
  1291. delete data[key];
  1292. }
  1293. if (data.chain) {
  1294. let need = [],
  1295. drop = [],
  1296. links = data.chain.split('.');
  1297. for (let link of links)
  1298. if (!isVast(link))
  1299. need.push(link);
  1300. else
  1301. drop.push(link);
  1302. _console.log('Dropped from the chain:', ...drop);
  1303. data.chain = need.join('.');
  1304. }
  1305. }
  1306. return data;
  1307. }
  1308.  
  1309. _document.addEventListener(
  1310. 'DOMContentLoaded', function() {
  1311. if ('video_balancer_options' in win && 'event_callback' in win) {
  1312. log('Moonwalk');
  1313. if (video_balancer_options.adv)
  1314. removeVast(video_balancer_options.adv);
  1315. if ('_mw_adb' in win)
  1316. Object.defineProperty(win, '_mw_adb', {
  1317. get: () => false,
  1318. set: () => true
  1319. });
  1320. } else if (win.startKodikPlayer !== void 0) {
  1321. log('Kodik');
  1322. // skip attempt to block access to HD resolutions
  1323. let chainCall = new Proxy({}, { get: () => () => chainCall });
  1324. if ($ && $.prototype && $.prototype.addClass) {
  1325. let $addClass = $.prototype.addClass;
  1326. $.prototype.addClass = function (className) {
  1327. if (className === 'blocked')
  1328. return chainCall;
  1329. return $addClass.apply(this, arguments);
  1330. };
  1331. }
  1332. // remove ad links from the metadata
  1333. let _ajax = win.$.ajax;
  1334. win.$.ajax = (params, ...args) => {
  1335. if (params.success) {
  1336. let _s = params.success;
  1337. params.success = (data, ...args) => _s(removeVast(data), ...args);
  1338. }
  1339. return _ajax(params, ...args);
  1340. }
  1341. } else if (win.getnextepisode && win.uppodEvent) {
  1342. log('Share-Serials.net');
  1343. scriptLander(
  1344. function() {
  1345. let _setInterval = win.setInterval,
  1346. _setTimeout = win.setTimeout,
  1347. _toString = Function.prototype.call.bind(Function.prototype.toString);
  1348. win.setInterval = function(func) {
  1349. if (func instanceof Function && _toString(func).includes('_delay')) {
  1350. let intv = _setInterval.call(
  1351. this, function() {
  1352. _setTimeout.call(
  1353. this, function(intv) {
  1354. clearInterval(intv);
  1355. let timer = _document.querySelector('#timer');
  1356. if (timer)
  1357. timer.click();
  1358. }, 100, intv);
  1359. func.call(this);
  1360. }, 5
  1361. );
  1362.  
  1363. return intv;
  1364. }
  1365. return _setInterval.apply(this, arguments);
  1366. };
  1367. win.setTimeout = function(func) {
  1368. if (func instanceof Function && _toString(func).includes('adv_showed'))
  1369. return _setTimeout.call(this, func, 0);
  1370. return _setTimeout.apply(this, arguments);
  1371. };
  1372. }
  1373. );
  1374. } else if ('ADC' in win) {
  1375. log('vjs-creatives plugin in');
  1376. let replacer = (obj) => {
  1377. for (let name in obj)
  1378. if (obj[name] instanceof Function)
  1379. obj[name] = () => null;
  1380. };
  1381. replacer(win.ADC);
  1382. replacer(win.currentAdSlot);
  1383. }
  1384. UberVK: {
  1385. if (!inIFrame)
  1386. break UberVK;
  1387. let oddNames = 'HD' in win &&
  1388. !Object.getOwnPropertyNames(win).every(n => !n.startsWith('_0x'));
  1389. if (!oddNames)
  1390. break UberVK;
  1391. log('UberVK');
  1392. XMLHttpRequest.prototype.open = () => {
  1393. throw 404;
  1394. };
  1395. }
  1396. }, false
  1397. );
  1398. let _hasOwnProperty = win.Function.prototype.apply.bind(win.Object.prototype.hasOwnProperty);
  1399. let _construct = win.Reflect.construct;
  1400. win.addEventListener('load', () => {
  1401. if ('Playerjs' in win) {
  1402. log('Playerjs');
  1403. win.Playerjs = new Proxy(win.Playerjs, {
  1404. construct (fn, args) {
  1405. let params = args[0];
  1406. if (params && typeof params === 'object') {
  1407. delete params.preroll;
  1408. params = removeVast(params);
  1409. Object.defineProperty(params, 'hasOwnProperty', {
  1410. value: function(...args) {
  1411. let res = _hasOwnProperty(this, args);
  1412. if (typeof args[0] === 'string' && args[0].startsWith('vast_') &&
  1413. res && params[args[0]]) {
  1414. _console.log(`Removed params.${args[0]}`, params[args[0]]);
  1415. delete params[args[0]];
  1416. return false;
  1417. }
  1418. return res;
  1419. },
  1420. enumerable: false,
  1421. configurable: true
  1422. });
  1423. }
  1424. return _construct(fn, args);
  1425. }
  1426. });
  1427. }
  1428. }, false);
  1429. }
  1430.  
  1431. // Applies wrapper function on the current page and all newly created same-origin iframes
  1432. // This is used to prevent trick which allows to get fresh page API through newly created same-origin iframes
  1433. function deepWrapAPI(wrapper) {
  1434. let wrapped = new WeakSet(),
  1435. _get_contentWindow = () => null,
  1436. log = (...args) => false && _console.log(...args);
  1437. let wrapAPI = root => {
  1438. if (!root || wrapped.has(root))
  1439. return;
  1440. wrapped.add(root);
  1441. try {
  1442. wrapper(root instanceof HTMLIFrameElement ? _get_contentWindow(root) : root);
  1443. log('Wrapped API in', (root === win) ? "main window." : root);
  1444. } catch(e) {
  1445. log('Failed to wrap API in', (root === win) ? "main window." : root, '\n', e);
  1446. }
  1447. };
  1448.  
  1449. // wrap API on contentWindow access
  1450. let _apply = Function.prototype.apply;
  1451. let _contentWindow = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, 'contentWindow');
  1452. _get_contentWindow = _apply.bind(_contentWindow.get);
  1453. _contentWindow.get = function() {
  1454. wrapAPI(this);
  1455. return _get_contentWindow(this);;
  1456. };
  1457. Object.defineProperty(HTMLIFrameElement.prototype, 'contentWindow', _contentWindow);
  1458.  
  1459. // wrap API on contentDocument access
  1460. let _contentDocument = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, 'contentDocument');
  1461. let _get_contentDocument = _apply.bind(_contentDocument.get);
  1462. _contentDocument.get = function() {
  1463. wrapAPI(this);
  1464. return _get_contentDocument(this);
  1465. };
  1466. Object.defineProperty(HTMLIFrameElement.prototype, 'contentDocument', _contentDocument);
  1467.  
  1468. // manual children objects traverser to avoid issues
  1469. // with calling querySelectorAll on wrong types of objects
  1470. let _nodeType = _apply.bind(Object.getOwnPropertyDescriptor(_Node, 'nodeType').get);
  1471. let _childNodes = _apply.bind(Object.getOwnPropertyDescriptor(_Node, 'childNodes').get);
  1472. let _ELEMENT_NODE = _Node.ELEMENT_NODE;
  1473. let _DOCUMENT_FRAGMENT_NODE = _Node.DOCUMENT_FRAGMENT_NODE
  1474. let wrapFrames = root => {
  1475. if (_nodeType(root) !== _ELEMENT_NODE && _nodeType(root) !== _DOCUMENT_FRAGMENT_NODE)
  1476. return; // only process nodes which may contain an IFRAME or be one
  1477. if (root instanceof HTMLIFrameElement) {
  1478. wrapAPI(root);
  1479. return;
  1480. }
  1481. for (let child of _childNodes(root))
  1482. wrapFrames(child);
  1483. };
  1484.  
  1485. // wrap API in a newly appended iframe objects
  1486. let _appendChild = _apply.bind(Node.prototype.appendChild);
  1487. Node.prototype.appendChild = function appendChild() {
  1488. '[native code]';
  1489. let res = _appendChild(this, arguments);
  1490. wrapFrames(arguments[0]);
  1491. return res;
  1492. };
  1493.  
  1494. // wrap API in iframe objects created with innerHTML of element on page
  1495. let _innerHTML = Object.getOwnPropertyDescriptor(_Element, 'innerHTML');
  1496. let _set_innerHTML = _apply.bind(_innerHTML.set);
  1497. _innerHTML.set = function() {
  1498. _set_innerHTML(this, arguments);
  1499. if (_document.contains(this))
  1500. wrapFrames(this);
  1501. };
  1502. Object.defineProperty(_Element, 'innerHTML', _innerHTML);
  1503.  
  1504. wrapAPI(win);
  1505. }
  1506.  
  1507. // piguiqproxy.com / zmctrack.net circumvention and onerror callback prevention
  1508. scriptLander(
  1509. () => {
  1510. // onerror callback blacklist
  1511. let masks = [],
  1512. //blockAll = /(^|\.)(rutracker-org\.appspot\.com)$/,
  1513. isBlocked = url => masks.some(mask => mask.test(url));// || blockAll.test(location.hostname);
  1514. for (let filter of [// blacklist
  1515. // global
  1516. '/adv/www/',
  1517. // adservers
  1518. '||185.87.50.147^',
  1519. '||10root25.website^', '||24video.xxx^',
  1520. '||adlabs.ru^', '||adspayformymortgage.win^', '||amgload.net^', '||aviabay.ru^',
  1521. '||bgrndi.com^', '||brokeloy.com^',
  1522. '||cdnjs-aws.ru^','||cnamerutor.ru^',
  1523. '||directadvert.ru^', '||dsn-fishki.ru^', '||docfilms.info^', '||dreadfula.ru^',
  1524. '||et-cod.com^', '||et-code.ru^', '||etcodes.com^',
  1525. '||franecki.net^', '||film-doma.ru^',
  1526. '||free-torrent.org^', '||free-torrent.pw^',
  1527. '||free-torrents.org^', '||free-torrents.pw^',
  1528. '||game-torrent.info^', '||gocdn.ru^',
  1529. '||hdkinoshka.com^', '||hghit.com^', '||hindcine.net^',
  1530. '||kinotochka.net^', '||kinott.com^', '||kinott.ru^',
  1531. '||klcheck.com^', '||kuveres.com^',
  1532. '||lepubs.com^', '||luxadv.com^', '||luxup.ru^', '||luxupcdna.com^',
  1533. '||marketgid.com^', '||mebablo.com^', '||mixadvert.com^', '||mxtads.com^',
  1534. '||nickhel.com^',
  1535. '||oconner.biz^', '||oconner.link^', '||octoclick.net^', '||octozoon.org^',
  1536. '||pigiuqproxy.com^', '||piguiqproxy.com^', '||pkpojhc.com^',
  1537. '||psma01.com^', '||psma02.com^', '||psma03.com^',
  1538. '||rcdn.pro^', '||recreativ.ru^', '||redtram.com^', '||regpole.com^',
  1539. '||rootmedia.ws^', '||ruttwind.com^', '||rutvind.com^',
  1540. '||skidl.ru^', '||smi2.net^', '||smcheck.org^',
  1541. '||torvind.com^', '||traffic-media.co^', '||trafmag.com^', '||trustjs.net^', '||ttarget.ru^',
  1542. '||u-dot-id-adtool.appspot.com^', '||utarget.ru^',
  1543. '||webadvert-gid.ru^', '||webadvertgid.ru^',
  1544. '||xxuhter.ru^',
  1545. '||yuiout.online^',
  1546. '||zmctrack.net^', '||zoom-film.ru^'])
  1547. masks.push(new RegExp(
  1548. filter.replace(/([\\/[\].+?(){}$])/g, '\\$1')
  1549. .replace(/\*/g, '.*?')
  1550. .replace(/\^(?!$)/g,'\\.?[^\\w%._-]')
  1551. .replace(/\^$/,'\\.?([^\\w%._-]|$)')
  1552. .replace(/^\|\|/,'^(ws|http)s?:\\/+([^/.]+\\.)*?'),
  1553. 'i'));
  1554. // main script
  1555. deepWrapAPI(root => {
  1556. let _call = root.Function.prototype.call,
  1557. _defineProperty = root.Object.defineProperty,
  1558. _getOwnPropertyDescriptor = root.Object.getOwnPropertyDescriptor;
  1559. onerror: {
  1560. // 'onerror' handler for scripts from blacklisted sources
  1561. let scriptMap = new WeakMap();
  1562. let _Reflect_apply = root.Reflect.apply,
  1563. _HTMLScriptElement = root.HTMLScriptElement,
  1564. _HTMLImageElement = root.HTMLImageElement;
  1565. let _get_tagName = _call.bind(_getOwnPropertyDescriptor(root.Element.prototype, 'tagName').get),
  1566. _get_scr_src = _call.bind(_getOwnPropertyDescriptor(_HTMLScriptElement.prototype, 'src').get),
  1567. _get_img_src = _call.bind(_getOwnPropertyDescriptor(_HTMLImageElement.prototype, 'src').get);
  1568. let _get_src = node => {
  1569. if (node instanceof _HTMLScriptElement)
  1570. return _get_scr_src(node);
  1571. if (node instanceof _HTMLImageElement)
  1572. return _get_img_src(node);
  1573. return void 0
  1574. };
  1575. let _onerror = _getOwnPropertyDescriptor(root.HTMLElement.prototype, 'onerror'),
  1576. _set_onerror = _call.bind(_onerror.set);
  1577. _onerror.get = function() {
  1578. return scriptMap.get(this) || null;
  1579. };
  1580. _onerror.set = function(callback) {
  1581. if (typeof callback !== 'function') {
  1582. scriptMap.delete(this);
  1583. _set_onerror(this, callback);
  1584. return;
  1585. }
  1586. scriptMap.set(this, callback);
  1587. _set_onerror(this, function() {
  1588. let src = _get_src(this);
  1589. if (isBlocked(src)) {
  1590. _console.warn(`Blocked "onerror" callback from ${_get_tagName(this)}: ${src}`);
  1591. return;
  1592. }
  1593. _Reflect_apply(scriptMap.get(this), this, arguments);
  1594. });
  1595. };
  1596. _defineProperty(root.HTMLElement.prototype, 'onerror', _onerror);
  1597. }
  1598. // Simplistic WebSocket wrapper for Maxthon and Firefox before v58
  1599. WSWrap: { // once again seems required in Google Chrome and similar browsers due to zmctrack.net -_-
  1600. if (true /*/Maxthon/.test(navigator.appVersion) ||
  1601. 'InstallTrigger' in win && 'StopIteration' in win*/) {
  1602. let _ws = _getOwnPropertyDescriptor(root, 'WebSocket');
  1603. if (!_ws)
  1604. break WSWrap;
  1605. _ws.value = new Proxy(_ws.value, {
  1606. construct: (ws, args) => {
  1607. if (isBlocked(args[0])) {
  1608. _console.log('Blocked WS connection:', args[0]);
  1609. return {};
  1610. }
  1611. return new ws(...args);
  1612. }
  1613. });
  1614. _defineProperty(root, 'WebSocket', _ws);
  1615. }
  1616. }
  1617. untrustedClick: {
  1618. // Block popular method to open a new window in Google Chrome by dispatching a custom click
  1619. // event on a newly created anchor with _blank target. Untrusted events must not open new windows.
  1620. let _dispatchEvent = _call.bind(root.EventTarget.prototype.dispatchEvent);
  1621. root.EventTarget.prototype.dispatchEvent = function dispatchEvent(e) {
  1622. if (!e.isTrusted && e.type === 'click' && e.constructor.name === 'MouseEvent' &&
  1623. !this.parentNode && this.tagName === 'A' && this.target[0] === '_') {
  1624. _console.log('Blocked dispatching a click event on a parentless anchor:', this);
  1625. return;
  1626. }
  1627. return _dispatchEvent(this, ...arguments);
  1628. };
  1629. }
  1630. // XHR Wrapper
  1631. let _proto = void 0;
  1632. try {
  1633. _proto = root.XMLHttpRequest.prototype;
  1634. } catch(ignore) {
  1635. return;
  1636. };
  1637. // blacklist of domains where all third-party requests are ignored
  1638. let ondomains = /(^|[/.@])oane\.ws($|[:/])/i;
  1639. // highly suspicious URLs
  1640. let suspicious = /^(https?:)?\/\/(?!(rutube|worldoftanks)\.ru[:/])(csp-)?([a-z0-9]{6}){1,2}\.ru\//i;
  1641. 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;
  1642. let on_post_ban = /^(https?:)?\/\/(?!(rutube|worldoftanks)\.ru[:/])(csp-)?([a-z0-9]{6}){1,2}\.ru\/([a-z0-9]{6,})$/i;
  1643. 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;
  1644. let more_y_direct = /^(https?:)?\/\/((([^.]+\.)??(24smi\.org|(echo\.msk|drive2|kakprosto|liveinternet|razlozhi)\.ru)\/(.{290,}|[a-z0-9/_-]{100,}))|yastatic\.net\/.*?\/chunks\/promo\/.*)$/i;
  1645. let whitelist = /^(https?:)?\/\/yandex\.ru\/yobject$/;
  1646. let fabPatterns = /\/fuckadblock/i;
  1647.  
  1648. let blockedUrls = new Set();
  1649. function checkRequest(fname, method, url) {
  1650. let block = isBlocked(url) ||
  1651. ondomains.test(location.hostname) && !ondomains.test(url) ||
  1652. method !== 'POST' && on_get_ban.test(url) ||
  1653. method === 'POST' && on_post_ban.test(url) ||
  1654. yandex_direct.test(url) || more_y_direct.test(url);
  1655. let allow = block && whitelist.test(url) ||
  1656. // 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
  1657. (block && method === 'script.src' &&
  1658. root.location.pathname === '/images/search' && root.location.hostname.startsWith('yandex.') &&
  1659. url.startsWith('http') && url.includes('/images/')) || // Direct URLs are similar, but don't have protocol for some reason
  1660. (block && root.location.hostname === 'widgets.kinopoisk.ru' && url.includes('/static/main.js?')) ||
  1661. (block && !url.startsWith('http') && // drive2.ru hid a little CSS style in their requests which shows page content like this
  1662. (root.location.hostname === 'drive2.ru' || root.location.hostname.endsWith('.drive2.ru')));
  1663. if (allow) {
  1664. block = false;
  1665. _console.warn(`Allowed ${fname} ${method} request:`, url, 'from', root.location.href);
  1666. }
  1667. if (block) {
  1668. if (!blockedUrls.has(url)) // don't repeat log if the same URL were blocked more than once
  1669. _console.warn(`Blocked ${fname} ${method} request:`, url, 'from', root.location.href);
  1670. blockedUrls.add(url);
  1671. return true;
  1672. }
  1673. if (!allow && suspicious.test(url))
  1674. _console.warn(`Suspicious ${fname} ${method} request:`, url, 'from', root.location.href);
  1675. return false;
  1676. }
  1677.  
  1678. // workaround for a broken weather mini-map on Yandex
  1679. let skip_xhr_check = false;
  1680. if (root.location.hostname.startsWith('yandex.') &&
  1681. root.location.pathname.startsWith('/pogoda/') ||
  1682. root.location.hostname.endsWith('.kakprosto.ru'))
  1683. skip_xhr_check = true;
  1684.  
  1685. let xhrStopList = new WeakSet();
  1686. let _open = root.Function.prototype.apply.bind(_proto.open);
  1687. _proto.open = function open() {
  1688. '[native code]';
  1689. return !skip_xhr_check && checkRequest('xhr', ...arguments) ?
  1690. (xhrStopList.add(this), void 0) : _open(this, arguments);
  1691. };
  1692. ['send', 'setRequestHeader', 'getAllResponseHeaders'].forEach(
  1693. name => {
  1694. let func = _proto[name];
  1695. _proto[name] = function(...args) {
  1696. return xhrStopList.has(this) ? null : func.apply(this, args);
  1697. };
  1698. }
  1699. );
  1700. // simulate readyState === 1 for blocked requests
  1701. let _readyState = Object.getOwnPropertyDescriptor(_proto, 'readyState');
  1702. let _get_readyState = root.Function.prototype.apply.bind(_readyState.get);
  1703. _readyState.get = function() {
  1704. return xhrStopList.has(this) ? 1 : _get_readyState(this, arguments);
  1705. }
  1706. Object.defineProperty(_proto, 'readyState', _readyState);
  1707.  
  1708. let _fetch = root.Function.prototype.apply.bind(root.fetch);
  1709. root.fetch = function fetch() {
  1710. '[native code]';
  1711. let url = arguments[0];
  1712. let method = arguments[1] ? arguments[1].method : void 0;
  1713. if (arguments[0] instanceof Request) {
  1714. method = url.method;
  1715. url = url.url;
  1716. }
  1717. if (checkRequest('fetch', method, url))
  1718. return new Promise(() => null);
  1719. return _fetch(root, arguments);
  1720. };
  1721.  
  1722. let _script_src = Object.getOwnPropertyDescriptor(root.HTMLScriptElement.prototype, 'src');
  1723. let _script_src_set = root.Function.prototype.apply.bind(_script_src.set);
  1724. let _dispatchEvent = root.Function.prototype.call.bind(root.EventTarget.prototype.dispatchEvent);
  1725. _script_src.set = function(src) {
  1726. if (fabPatterns.test(src)) {
  1727. _console.warn(`Blocked set script.src request:`, src);
  1728. deployFABStub(root);
  1729. setTimeout(() => {
  1730. let e = root.document.createEvent('Event');
  1731. e.initEvent('load', false, false);
  1732. _dispatchEvent(this, e);
  1733. }, 0);
  1734. return;
  1735. }
  1736. return checkRequest('set', 'script.src', src) || _script_src_set(this, arguments);
  1737. };
  1738. Object.defineProperty(root.HTMLScriptElement.prototype, 'src', _script_src);
  1739.  
  1740. let adregain_pattern = /ggg==" alt="advertisement"/;
  1741. if (root.self !== root.top) { // in IFrame
  1742. let _write = Function.prototype.call.bind(root.document.write);
  1743. root.document.write = function write(text, ...args) {
  1744. "[native code]";
  1745. if (adregain_pattern.test(text)) {
  1746. _console.log('Skipped AdRegain frame.');
  1747. return _write(this, '');
  1748. }
  1749. return _write(this, text, ...args);
  1750. };
  1751. }
  1752. });
  1753.  
  1754. win.stop = () => {
  1755. _console.warn('window.stop() ...y tho?');
  1756. for (let sheet of _document.styleSheets)
  1757. if (sheet.disabled) {
  1758. sheet.disabled = false;
  1759. _console.log('Re-enabled:', sheet);
  1760. }
  1761. }
  1762. }, deepWrapAPI
  1763. );
  1764.  
  1765. // === Helper functions ===
  1766.  
  1767. // function to search and remove nodes by content
  1768. // selector - standard CSS selector to define set of nodes to check
  1769. // words - regular expression to check content of the suspicious nodes
  1770. // params - object with multiple extra parameters:
  1771. // .log - display log in the console
  1772. // .hide - set display to none instead of removing from the page
  1773. // .parent - parent node to remove if content is found in the child node
  1774. // .siblings - number of simling nodes to remove (excluding text nodes)
  1775. let scRemove = (node) => node.parentNode.removeChild(node);
  1776. let scHide = function(node) {
  1777. let style = _getAttribute(node, 'style') || '',
  1778. hide = ';display:none!important;';
  1779. if (style.indexOf(hide) < 0)
  1780. _setAttribute(node, 'style', style + hide);
  1781. };
  1782.  
  1783. function scissors (selector, words, scope, params) {
  1784. let logger = (...args) => { if (params.log) _console.log(...args) };
  1785. if (!scope.contains(_document.body))
  1786. logger('[s] scope', scope);
  1787. let remFunc = (params.hide ? scHide : scRemove),
  1788. iterFunc = (params.siblings > 0 ? 'nextElementSibling' : 'previousElementSibling'),
  1789. toRemove = [],
  1790. siblings;
  1791. for (let node of scope.querySelectorAll(selector)) {
  1792. // drill up to a parent node if specified, break if not found
  1793. if (params.parent) {
  1794. let old = node;
  1795. node = node.closest(params.parent);
  1796. if (node === null || node.contains(scope)) {
  1797. logger('[s] went out of scope with', old);
  1798. continue;
  1799. }
  1800. }
  1801. logger('[s] processing', node);
  1802. if (toRemove.includes(node))
  1803. continue;
  1804. if (words.test(node.innerHTML)) {
  1805. // skip node if already marked for removal
  1806. logger('[s] marked for removal');
  1807. toRemove.push(node);
  1808. // add multiple nodes if defined more than one sibling
  1809. siblings = Math.abs(params.siblings) || 0;
  1810. while (siblings) {
  1811. node = node[iterFunc];
  1812. if (!node) break; // can't go any further - exit
  1813. logger('[s] adding sibling node', node);
  1814. toRemove.push(node);
  1815. siblings -= 1;
  1816. }
  1817. }
  1818. }
  1819. let toSkip = [];
  1820. for (let node of toRemove)
  1821. if (!toRemove.every(other => other === node || !node.contains(other)))
  1822. toSkip.push(node);
  1823. if (toRemove.length)
  1824. logger(`[s] proceeding with ${params.hide?'hide':'removal'} of`, toRemove, `skip`, toSkip);
  1825. for (let node of toRemove) if (!toSkip.includes(node))
  1826. remFunc(node);
  1827. }
  1828.  
  1829. // function to perform multiple checks if ads inserted with a delay
  1830. // by default does 30 checks withing a 3 seconds unless nonstop mode specified
  1831. // also does 1 extra check when a page completely loads
  1832. // selector and words - passed dow to scissors
  1833. // params - object with multiple extra parameters:
  1834. // .log - display log in the console
  1835. // .root - selector to narrow down scope to scan;
  1836. // .observe - if true then check will be performed continuously;
  1837. // Other parameters passed down to scissors.
  1838. function gardener(selector, words, params) {
  1839. let logger = (...args) => { if (params.log) _console.log(...args) };
  1840. params = params || {};
  1841. logger(`[gardener] selector: '${selector}' detector: ${words} options: ${JSON.stringify(params)}`);
  1842. let scope;
  1843. let globalScope = [_de];
  1844. let domLoaded = false;
  1845. let getScope = root => root ? _de.querySelectorAll(root) : globalScope;
  1846. let onevent = e => {
  1847. logger(`[gardener] cleanup on ${Object.getPrototypeOf(e)} "${e.type}"`);
  1848. for (let node of scope)
  1849. scissors(selector, words, node, params);
  1850. };
  1851. let repeater = n => {
  1852. if (!domLoaded && n) {
  1853. setTimeout(repeater, 500, n - 1);
  1854. scope = getScope(params.root);
  1855. if (!scope) // exit if the root element is not present on the page
  1856. return 0;
  1857. onevent({type: 'Repeater'});
  1858. }
  1859. };
  1860. repeater(20);
  1861. _document.addEventListener(
  1862. 'DOMContentLoaded', (e) => {
  1863. domLoaded = true;
  1864. // narrow down scope to a specific element
  1865. scope = getScope(params.root);
  1866. if (!scope) // exit if the root element is not present on the page
  1867. return 0;
  1868. logger('[g] scope', scope);
  1869. // add observe mode if required
  1870. if (params.observe) {
  1871. let params = { childList:true, subtree: true };
  1872. let observer = new MutationObserver(
  1873. function(ms) {
  1874. for (let m of ms)
  1875. if (m.addedNodes.length)
  1876. onevent(m);
  1877. }
  1878. );
  1879. for (let node of scope)
  1880. observer.observe(node, params);
  1881. logger('[g] observer enabled');
  1882. }
  1883. onevent(e);
  1884. }, false);
  1885. // wait for a full page load to do one extra cut
  1886. win.addEventListener('load', onevent, false);
  1887. }
  1888.  
  1889. // wrap popular methods to open a new tab to catch specific behaviours
  1890. function createWindowOpenWrapper(openFunc) {
  1891. let _createElement = _Document.createElement,
  1892. _appendChild = _Element.appendChild,
  1893. fakeNative = (f) => (f.toString = () => `function ${f.name}() { [native code] }`);
  1894.  
  1895. let nt = new nullTools();
  1896. fakeNative(openFunc);
  1897.  
  1898. let parser = _createElement.call(_document, 'a');
  1899. let openWhitelist = (url, parent) => {
  1900. parser.href = url;
  1901. return parser.hostname === 'www.imdb.com' || parser.hostname === 'www.kinopoisk.ru' ||
  1902. parent.hostname === 'radikal.ru' && url === void 0;
  1903. };
  1904.  
  1905. let redefineOpen = (root) => {
  1906. if ('open' in root) {
  1907. let _open = root.open.bind(root);
  1908. nt.define(root, 'open', (...args) => {
  1909. if (openWhitelist(args[0], location)) {
  1910. _console.log('Whitelisted popup:', ...args);
  1911. return _open(...args);
  1912. }
  1913. return openFunc(...args);
  1914. });
  1915. }
  1916. };
  1917. redefineOpen(win);
  1918.  
  1919. function createElement() {
  1920. '[native code]';
  1921. let el = _createElement.apply(this, arguments);
  1922. // redefine window.open in first-party frames
  1923. if (el instanceof HTMLIFrameElement || el instanceof HTMLObjectElement)
  1924. el.addEventListener('load', (e) => {
  1925. try {
  1926. redefineOpen(e.target.contentWindow);
  1927. } catch(ignore) {}
  1928. }, false);
  1929. return el;
  1930. }
  1931. fakeNative(createElement);
  1932.  
  1933. let redefineCreateElement = (obj) => {
  1934. for (let root of [obj.document, _Document]) if ('createElement' in root)
  1935. nt.define(root, 'createElement', createElement);
  1936. };
  1937. redefineCreateElement(win);
  1938.  
  1939. // wrap window.open in newly added first-party frames
  1940. _Element.appendChild = function appendChild() {
  1941. '[native code]';
  1942. let el = _appendChild.apply(this, arguments);
  1943. if (el instanceof HTMLIFrameElement)
  1944. try {
  1945. redefineOpen(el.contentWindow);
  1946. redefineCreateElement(el.contentWindow);
  1947. } catch(ignore) {}
  1948. return el;
  1949. };
  1950. fakeNative(_Element.appendChild);
  1951. }
  1952.  
  1953. // Function to catch and block various methods to open a new window with 3rd-party content.
  1954. // Some advertisement networks went way past simple window.open call to circumvent default popup protection.
  1955. // This funciton blocks window.open, ability to restore original window.open from an IFRAME object,
  1956. // ability to perform an untrusted (not initiated by user) click on a link, click on a link without a parent
  1957. // node or simply a link with piece of javascript code in the HREF attribute.
  1958. function preventPopups() {
  1959. // call sandbox-me if in iframe and not whitelisted
  1960. if (inIFrame) {
  1961. win.top.postMessage({ name: 'sandbox-me', href: win.location.href }, '*');
  1962. return;
  1963. }
  1964.  
  1965. scriptLander(() => {
  1966. let nt = new nullTools({log:true});
  1967. let open = (...args) => {
  1968. '[native code]';
  1969. _console.warn('Site attempted to open a new window', ...args);
  1970. return {
  1971. document: nt.proxy({
  1972. write: nt.func({}, 'write'),
  1973. writeln: nt.func({}, 'writeln')
  1974. }),
  1975. location: nt.proxy({})
  1976. };
  1977. };
  1978.  
  1979. createWindowOpenWrapper(open);
  1980.  
  1981. _console.log('Popup prevention enabled.');
  1982. }, nullTools, createWindowOpenWrapper);
  1983. }
  1984.  
  1985. // Helper function to close background tab if site opens itself in a new tab and then
  1986. // loads a 3rd-party page in the background one (thus performing background redirect).
  1987. function preventPopunders() {
  1988. // create "close_me" event to call high-level window.close()
  1989. let eventName = `close_me_${Math.random().toString(36).substr(2)}`;
  1990. let callClose = () => {
  1991. _console.log('close call');
  1992. window.close();
  1993. };
  1994. window.addEventListener(eventName, callClose, true);
  1995.  
  1996. scriptLander(() => {
  1997. // get host of a provided URL with help of an anchor object
  1998. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  1999. let parseURL = _document.createElement('A');
  2000. let getHost = url => {
  2001. parseURL.href = url;
  2002. return parseURL.hostname
  2003. };
  2004. // site went to a new tab and attempts to unload
  2005. // call for high-level close through event
  2006. let closeWindow = () => window.dispatchEvent(new CustomEvent(eventName, {}));
  2007. // check is URL local or goes to different site
  2008. let isLocal = (url) => {
  2009. if (url === location.pathname || url === location.href)
  2010. return true; // URL points to current pathname or full address
  2011. let host = getHost(url);
  2012. let site = location.hostname;
  2013. return host !== '' && // URLs with unusual protocol may have empty 'host'
  2014. (site === host || site.endsWith(`.${host}`) || host.endsWith(`.${site}`));
  2015. };
  2016.  
  2017. let _open = window.open.bind(window);
  2018. let open = (...args) => {
  2019. '[native code]';
  2020. let url = args[0];
  2021. if (url && isLocal(url))
  2022. window.addEventListener('beforeunload', closeWindow, true);
  2023. return _open(...args);
  2024. };
  2025.  
  2026. createWindowOpenWrapper(open);
  2027.  
  2028. _console.log("Background redirect prevention enabled.");
  2029. }, `let eventName="${eventName}"`, nullTools, createWindowOpenWrapper);
  2030. }
  2031.  
  2032. // Mix between check for popups and popunders
  2033. // Significantly more agressive than both and can't be used as universal solution
  2034. function preventPopMix() {
  2035. if (inIFrame) {
  2036. win.top.postMessage({ name: 'sandbox-me', href: win.location.href }, '*');
  2037. return;
  2038. }
  2039.  
  2040. // create "close_me" event to call high-level window.close()
  2041. let eventName = `close_me_${Math.random().toString(36).substr(2)}`;
  2042. let callClose = () => {
  2043. _console.log('close call');
  2044. window.close();
  2045. };
  2046. window.addEventListener(eventName, callClose, true);
  2047.  
  2048. scriptLander(() => {
  2049. let _open = window.open,
  2050. parseURL = _document.createElement('A');
  2051. // get host of a provided URL with help of an anchor object
  2052. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  2053. let getHost = (url) => {
  2054. parseURL.href = url;
  2055. return parseURL.host;
  2056. };
  2057. // site went to a new tab and attempts to unload
  2058. // call for high-level close through event
  2059. let closeWindow = () => {
  2060. _open(window.location,'_self');
  2061. window.dispatchEvent(new CustomEvent(eventName, {}));
  2062. };
  2063. // check is URL local or goes to different site
  2064. function isLocal(url) {
  2065. let loc = window.location;
  2066. if (url === loc.pathname || url === loc.href)
  2067. return true; // URL points to current pathname or full address
  2068. let host = getHost(url),
  2069. site = loc.host;
  2070. if (host === '')
  2071. return false; // URLs with unusual protocol may have empty 'host'
  2072. if (host.length > site.length)
  2073. [site, host] = [host, site];
  2074. return site.includes(host, site.length - host.length);
  2075. }
  2076.  
  2077. // add check for redirect for 5 seconds, then disable it
  2078. function checkRedirect() {
  2079. window.addEventListener('beforeunload', closeWindow, true);
  2080. setTimeout(closeWindow=>window.removeEventListener('beforeunload', closeWindow, true), 5000, closeWindow);
  2081. }
  2082.  
  2083. function open(url, name) {
  2084. '[native code]';
  2085. if (url && isLocal(url) && (!name || name === '_blank')) {
  2086. _console.warn('Suspicious local new window', arguments);
  2087. checkRedirect();
  2088. return _open.apply(this, arguments);
  2089. }
  2090. _console.warn('Blocked attempt to open a new window', arguments);
  2091. return {
  2092. document: {
  2093. write: () => {},
  2094. writeln: () => {}
  2095. }
  2096. };
  2097. }
  2098.  
  2099. function clickHandler(e) {
  2100. let link = e.target,
  2101. url = link.href||'';
  2102. if (e.targetParentNode && e.isTrusted || link.target !== '_blank') {
  2103. _console.log('Link', link, 'were created dinamically, but looks fine.');
  2104. return true;
  2105. }
  2106. if (isLocal(url) && link.target === '_blank') {
  2107. _console.log('Suspicious local link', link);
  2108. checkRedirect();
  2109. return;
  2110. }
  2111. _console.log('Blocked suspicious click on a link', link);
  2112. e.stopPropagation();
  2113. e.preventDefault();
  2114. }
  2115.  
  2116. createWindowOpenWrapper(open, clickHandler);
  2117.  
  2118. _console.log("Mixed popups prevention enabled.");
  2119. }, `let eventName="${eventName}"`, createWindowOpenWrapper);
  2120. }
  2121. // External listener for case when site known to open popups were loaded in iframe
  2122. // It will sandbox any iframe which will send message 'forbid.popups' (preventPopups sends it)
  2123. // Some sites replace frame's window.location with data-url to run in clean context
  2124. if (!inIFrame) window.addEventListener(
  2125. 'message', function(e) {
  2126. if (!e.data || e.data.name !== 'sandbox-me' || !e.data.href)
  2127. return;
  2128. let src = e.data.href;
  2129. for (let frame of _document.querySelectorAll('iframe'))
  2130. if (frame.contentWindow === e.source) {
  2131. if (frame.hasAttribute('sandbox')) {
  2132. if (!frame.sandbox.contains('allow-popups'))
  2133. return; // exit frame since it's already sandboxed and popups are blocked
  2134. // remove allow-popups if frame already sandboxed
  2135. frame.sandbox.remove('allow-popups');
  2136. } else
  2137. // set sandbox mode for troublesome frame and allow scripts, forms and a few other actions
  2138. // technically allowing both scripts and same-origin allows removal of the sandbox attribute,
  2139. // but to apply content must be reloaded and this script will re-apply it in the result
  2140. frame.setAttribute('sandbox','allow-forms allow-scripts allow-presentation allow-top-navigation allow-same-origin');
  2141. _console.log('Disallowed popups from iframe', frame);
  2142.  
  2143. // reload frame content to apply restrictions
  2144. if (!src) {
  2145. src = frame.src;
  2146. _console.log('Unable to get current iframe location, reloading from src', src);
  2147. } else
  2148. _console.log('Reloading iframe with URL', src);
  2149. frame.src = 'about:blank';
  2150. frame.src = src;
  2151. }
  2152. }, false
  2153. );
  2154.  
  2155. let evalPatternYandex = /{exports:{},id:r,loaded:!1}|containerId:(.|\r|\n)+params:/;
  2156. let evalPatternGeneric = /_0x|location\s*?=|location.href\s*?=|location.assign\(|open\(/i;
  2157. function selectiveEval(...patterns) {
  2158. if (patterns.length === 0)
  2159. patterns.push(evalPatternGeneric);
  2160. scriptLander(() => {
  2161. let _eval_def = Object.getOwnPropertyDescriptor(win, 'eval');
  2162. if (!_eval_def || !_eval_def.value) {
  2163. _console.warn('Unable to wrap window.eval.', _eval_def);
  2164. return;
  2165. }
  2166. let _eval_val = _eval_def.value;
  2167. _eval_def.value = function(...args) {
  2168. if (patterns.some(pattern => pattern.test(args[0]))) {
  2169. _console.warn(`Skipped eval of ${args[0].slice(0, 512)}\u2026`);
  2170. return null;
  2171. }
  2172. try {
  2173. return _eval_val.apply(this, args);
  2174. } catch(e) {
  2175. _console.log('Crash source:', args[0]);
  2176. throw e;
  2177. }
  2178. };
  2179. Object.defineProperty(win, 'eval', _eval_def);
  2180. }, `let patterns = [${patterns}];`);
  2181. }
  2182.  
  2183. // hides cookies by pattern and attempts to remove them if they already set
  2184. // also prevents setting new versions of such cookies
  2185. function selectiveCookies(scPattern = '', scPaths = []) {
  2186. scriptLander(() => {
  2187. let patterns = scPattern.split('|');
  2188. if (patterns[0] !== ';default') {
  2189. // Google Analytics cookies
  2190. patterns.push('_g(at?|id)|__utm[a-z]');
  2191. // Yandex ABP detection cookies
  2192. patterns.push('bltsr|blcrm');
  2193. } else
  2194. patterns.shift();
  2195. let blacklist = new RegExp(`(^|;\\s?)(${patterns.join('|')})($|=)`);
  2196. if (isFirefox && scPaths.length)
  2197. scPaths = scPaths.map(path => `${path}/`);
  2198. scPaths.push('/');
  2199. let _doc_proto = ('cookie' in _Document) ? _Document : Object.getPrototypeOf(_document);
  2200. let _cookie = Object.getOwnPropertyDescriptor(_doc_proto, 'cookie');
  2201. if (_cookie) {
  2202. let _set_cookie = Function.prototype.call.bind(_cookie.set);
  2203. let _get_cookie = Function.prototype.call.bind(_cookie.get);
  2204. let expireDate = 'Thu, 01 Jan 1970 00:00:01 UTC';
  2205. let expireAge = '-99999999';
  2206. let expireBase = `=;expires=${expireDate};Max-Age=${expireAge}`;
  2207. let expireAttempted = {};
  2208. // expire is called from cookie getter and doesn't know exact parameters used to set cookies present there
  2209. // so, it will use path=/ by default if scPaths wasn't set and attempt to set cookies on all parent domains
  2210. let expire = (cookie, that) => {
  2211. let domain = that.location.hostname.split('.'),
  2212. name = cookie.replace(/=.*/,'');
  2213. scPaths.forEach(path =>_set_cookie(that, `${name}${expireBase};path=${path}`));
  2214. while (domain.length > 1) {
  2215. try {
  2216. scPaths.forEach(
  2217. path => _set_cookie(that, `${name}${expireBase};domain=${domain.join('.')};path=${path}`)
  2218. );
  2219. } catch(e) { _console.warn(e); }
  2220. domain.shift();
  2221. }
  2222. expireAttempted[name] = true;
  2223. _console.log('Removing existing cookie:', cookie);
  2224. };
  2225. // skip setting unwanted cookies
  2226. _cookie.set = function(value) {
  2227. if (blacklist.test(value)) {
  2228. _console.warn('Ignored cookie:', value);
  2229. // try to remove same cookie if it already exists using exact values from the set string
  2230. if (blacklist.test(_get_cookie(this))) {
  2231. let parts = value.split(/;\s?/),
  2232. name = parts[0].replace(/=.*/,''),
  2233. newParts = [`${name}=`, `expires=${expireDate}`, `Max-Age=${expireAge}`],
  2234. skip = [name, 'expires', 'Max-Age'];
  2235. for (let part of parts)
  2236. if (!skip.includes(part.replace(/=.*/,'')))
  2237. newParts.push(part);
  2238. try {
  2239. _set_cookie(this, newParts.join(';'));
  2240. } catch(e) { _console.warn(e); }
  2241. _console.log('Removing existing cookie:', name);
  2242. }
  2243. return;
  2244. }
  2245. return _set_cookie(this, value);
  2246. };
  2247. // hide unwanted cookies from site
  2248. _cookie.get = function() {
  2249. let res = _get_cookie(this);
  2250. if (blacklist.test(res)) {
  2251. let stack = [];
  2252. for (let cookie of res.split(/;\s?/))
  2253. if (!blacklist.test(cookie))
  2254. stack.push(cookie);
  2255. else {
  2256. let name = cookie.replace(/=.*/,'');
  2257. if (expireAttempted[name]) {
  2258. _console.log('Unable to expire:', cookie);
  2259. expireAttempted[name] = false;
  2260. }
  2261. if (!(name in expireAttempted))
  2262. expire(cookie, this);
  2263. }
  2264. res = stack.join('; ');
  2265. }
  2266. return res;
  2267. };
  2268. Object.defineProperty(_doc_proto, 'cookie', _cookie);
  2269. _console.log('Active cookies:', win.document.cookie);
  2270. }
  2271. }, `let scPattern = "${scPattern}", scPaths = ${JSON.stringify(scPaths)}, isFirefox = ${isFirefox};`);
  2272. }
  2273.  
  2274. /*{ // simple toString wrapper, might be useful to prevent detection
  2275. '[native code]';
  2276. let _toString = Function.prototype.apply.bind(Function.prototype.toString);
  2277. let baseText = Function.prototype.toString.toString();
  2278. let protect = new WeakSet();
  2279. protect.add(_Document.createElement);
  2280. protect.add(_Node.appendChild);
  2281. protect.add(_Node.removeChild);
  2282. win.Function.prototype.toString = function() {
  2283. if (protect.has(this))
  2284. return baseText.replace('toString', this.name);
  2285. return _toString(this);
  2286. };
  2287. protect.add(Function.prototype.toString);
  2288. }*/
  2289.  
  2290. // Locates a node with specific text in Russian
  2291. // Uses table of substitutions for similar letters
  2292. let selectNodeByTextContent = (()=> {
  2293. let subs = {
  2294. // english & greek
  2295. 'А': 'AΑ', 'В': 'BΒ', 'Г':'Γ',
  2296. 'Е': 'EΕ', 'З': '3', 'К':'KΚ',
  2297. 'М': 'MΜ', 'Н': 'HΗ', 'О':'OΟ',
  2298. 'П': 'Π', 'Р': 'PΡ', 'С':'C',
  2299. 'Т': 'T', 'Ф': 'Φ', 'Х':'XΧ'
  2300. }
  2301. let regExpBuilder = text => new RegExp(
  2302. text.toUpperCase()
  2303. .split('')
  2304. .map(function(e){
  2305. return `${e in subs ? `[${e}${subs[e]}]` : (e === ' ' ? '\\s+' : e)}[\u200b\u200c\u200d]*`;
  2306. })
  2307. .join(''),
  2308. 'i');
  2309. let reMap = {};
  2310. return (re, opts = { root: _document.body }) => {
  2311. if (!re.test) {
  2312. if (!reMap[re])
  2313. reMap[re] = regExpBuilder(re);
  2314. re = reMap[re];
  2315. }
  2316.  
  2317. for (let child of opts.root.children)
  2318. if (re.test(child.textContent)) {
  2319. if (opts.shallow)
  2320. return child;
  2321. opts.root = child;
  2322. return selectNodeByTextContent(re, opts) || child;
  2323. }
  2324. }
  2325. })();
  2326.  
  2327. // webpackJsonp filter
  2328. function webpackJsonpFilter(blacklist, log = false) {
  2329. let _apply = Reflect.apply;
  2330. let _toString = Function.prototype.call.bind(Function.prototype.toString);
  2331. function wrapPush(webpack) {
  2332. let _push = webpack.push.bind(webpack);
  2333. Object.defineProperty(webpack, 'push', {
  2334. get: () => _push,
  2335. set: vl => {
  2336. _push = new Proxy(vl, {
  2337. apply: (push, obj, args) => {
  2338. wrapper: {
  2339. if (!(args[0] instanceof Array))
  2340. break wrapper;
  2341. let mainName;
  2342. if (args[0][2] instanceof Array && args[0][2][0] instanceof Array)
  2343. mainName = args[0][2][0][0];
  2344. let funs = args[0][1];
  2345. if (!(funs instanceof Object && !(funs instanceof Array)))
  2346. break wrapper;
  2347. for (let name in funs) {
  2348. if (typeof funs[name] !== 'function')
  2349. continue;
  2350. if (blacklist.test(_toString(funs[name])) && name !== mainName) {
  2351. let text = log ? _toString(funs[name]) : '';
  2352. funs[name] = () => _console.log(`Skip webpack ${name}`, text);
  2353. }
  2354. }
  2355. }
  2356. _console.log('webpack.push()');
  2357. return _apply(push, obj, args);
  2358. }
  2359. });
  2360. return true;
  2361. }
  2362. });
  2363. return webpack
  2364. }
  2365. let _webpackJsonp = wrapPush([]);
  2366. Object.defineProperty(win, 'webpackJsonp', {
  2367. get: () => _webpackJsonp,
  2368. set: vl => {
  2369. if (vl === _webpackJsonp)
  2370. return;
  2371. _console.log('new webpackJsonp', vl);
  2372. _webpackJsonp = wrapPush(vl);
  2373. return true;
  2374. }
  2375. });
  2376. }
  2377.  
  2378. // === Scripts for specific domains ===
  2379.  
  2380. let scripts = {};
  2381. // prevent popups and redirects block
  2382. // Popups
  2383. scripts.preventPopups = {
  2384. other: [
  2385. 'biqle.ru',
  2386. 'chaturbate.com',
  2387. 'dfiles.ru',
  2388. 'eporner.eu',
  2389. 'hentaiz.org',
  2390. 'mirrorcreator.com',
  2391. 'online-multy.ru',
  2392. 'radikal.ru', 'rumedia.ws',
  2393. 'tapehub.tech', 'thepiratebay.org',
  2394. 'unionpeer.com',
  2395. 'zippyshare.com'
  2396. ],
  2397. now: preventPopups
  2398. };
  2399. // Popunders (background redirect)
  2400. scripts.preventPopunders = {
  2401. other: [
  2402. 'lostfilm-online.ru',
  2403. 'mediafire.com', 'megapeer.org', 'megapeer.ru',
  2404. 'perfectgirls.net'
  2405. ],
  2406. now: preventPopunders
  2407. };
  2408. // PopMix (both types of popups encountered on site)
  2409. scripts['openload.co'] = {
  2410. other: ['oload.tv', 'oload.info'],
  2411. now: () => {
  2412. let nt = new nullTools();
  2413. nt.define(win, 'CNight', win.CoinHive);
  2414. if (location.pathname.startsWith('/embed/')) {
  2415. nt.define(win, 'BetterJsPop', {
  2416. add: ((a, b) => _console.warn('BetterJsPop.add', a, b)),
  2417. config: ((o) => _console.warn('BetterJsPop.config', o)),
  2418. Browser: { isChrome: true }
  2419. });
  2420. nt.define(win, 'isSandboxed', nt.func(null));
  2421. nt.define(win, 'adblock', false);
  2422. nt.define(win, 'adblock2', false);
  2423. } else preventPopMix();
  2424. }
  2425. };
  2426. scripts['turbobit.net'] = preventPopMix;
  2427.  
  2428. scripts['tapochek.net'] = () => {
  2429. // workaround for moradu.com/apu.php load error handler script, not sure which ad network is this
  2430. let _appendChild = Object.getOwnPropertyDescriptor(_Node, 'appendChild');
  2431. let _appendChild_value = _appendChild.value;
  2432. _appendChild.value = function appendChild(node) {
  2433. if (this === _document.body)
  2434. if ((node instanceof HTMLScriptElement || node instanceof HTMLStyleElement) &&
  2435. /^https?:\/\/[0-9a-f]{15}\.com\/\d+(\/|\.css)$/.test(node.src) ||
  2436. node instanceof HTMLDivElement && node.style.zIndex > 900000 &&
  2437. node.style.backgroundImage.includes('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'))
  2438. throw '...eenope!';
  2439. return _appendChild_value.apply(this, arguments);
  2440. };
  2441. Object.defineProperty(_Node, 'appendChild', _appendChild);
  2442.  
  2443. // disable window focus tricks and changing location
  2444. let focusHandlerName = /\WfocusAchieved\(/
  2445. let _toString = Function.prototype.call.bind(Function.prototype.toString);
  2446. let _setInterval = win.setInterval;
  2447. win.setInterval = (...args) => {
  2448. if (args.length && focusHandlerName.test(_toString(args[0]))) {
  2449. _console.log('skip setInterval for', ...args);
  2450. return -1;
  2451. }
  2452. return _setInterval(...args);
  2453. };
  2454. let _addEventListener = win.addEventListener;
  2455. win.addEventListener = function(...args) {
  2456. if (args.length && args[0] === 'focus' && focusHandlerName.test(_toString(args[1]))) {
  2457. _console.log('skip addEventListener for', ...args);
  2458. return void 0;
  2459. }
  2460. return _addEventListener.apply(this, args);
  2461. };
  2462.  
  2463. // generic popup prevention
  2464. preventPopups();
  2465. };
  2466.  
  2467. scripts['rustorka.com'] = {
  2468. other: ['rustorka.club', 'rustorka.innal.top', 'rustorka.lib', 'rustorka.net'],
  2469. now: () => {
  2470. selectiveEval(evalPatternGeneric, /antiadblock/);
  2471. selectiveCookies('adblock|u_count|gophp|st2|st3', ['/forum']);
  2472. scriptLander(() => {
  2473. // wrap window.open to catch a popup if it triggers
  2474. win.open = (...args) => {
  2475. _console.warn(`Site attempted to open "${args[0]}" in a new window.`);
  2476. location.replace(location.href);
  2477. return null;
  2478. };
  2479. window.addEventListener('DOMContentLoaded', () => {
  2480. let link = void 0;
  2481. _document.body.addEventListener('mousedown', e => {
  2482. link = e.target.closest('a, select, #fancybox-title-wrap');
  2483. }, false);
  2484. let _open = window.open.bind(window);
  2485. let _getAttribute = Function.prototype.call.bind(_Element.getAttribute);
  2486. win.open = (...args) => {
  2487. let url = args[0];
  2488. if (link instanceof HTMLAnchorElement) {
  2489. // third-party post links
  2490. let href = _getAttribute(link, 'href');
  2491. if (link.classList.contains('postLink') &&
  2492. !link.matches(`a[href*="${location.hostname}"]`) &&
  2493. (href === url || link.href === url))
  2494. return _open(...args);
  2495. // onclick # links
  2496. if (href === '#' && /window\.open/.test(_getAttribute(link, 'onclick')))
  2497. return _open(...args);
  2498. // force local links to load in the current window
  2499. if (href[0] === '/' || href.startsWith('./') || href.includes(`//${location.hostname}/`))
  2500. location.assign(href);
  2501. }
  2502. // list of image hostings under upload picture button (new comment)
  2503. if (link instanceof HTMLSelectElement &&
  2504. !url.includes(location.hostname) &&
  2505. link.value === url)
  2506. return _open(...args);
  2507. // open screenshot in a new window
  2508. if (link instanceof HTMLSpanElement &&
  2509. link.id === 'fancybox-title-wrap')
  2510. return _open(...args);
  2511. // looks like tabunder
  2512. if (link === null && url === location.href)
  2513. location.replace(url); // reload current page
  2514. // other cases
  2515. _console.warn(`Site attempted to open "${url}" in a new window. Source: `, link);
  2516. return {};
  2517. };
  2518. }, true);
  2519. }, nullTools)
  2520. }
  2521. };
  2522.  
  2523. // = other ======================================================================================
  2524. scripts['1tv.ru'] = {
  2525. other: ['mediavitrina.ru'],
  2526. now: () => scriptLander(() => {
  2527. let nt = new nullTools();
  2528. nt.define(win, 'EUMPAntiblockConfig', nt.proxy({url: '//www.1tv.ru/favicon.ico'}));
  2529. let disablePlugins = {
  2530. 'antiblock': false,
  2531. 'stat1tv': false
  2532. };
  2533. let _EUMPConfig = void 0;
  2534. let _EUMPConfig_set = x => {
  2535. if (x.plugins) {
  2536. x.plugins = x.plugins.filter(plugin => (plugin in disablePlugins) ? !(disablePlugins[plugin] = true) : true);
  2537. _console.warn(`Player plugins: active [${x.plugins}], disabled [${Object.keys(disablePlugins).filter(x => disablePlugins[x])}]`);
  2538. }
  2539. _EUMPConfig = x;
  2540. };
  2541. if ('EUMPConfig' in win)
  2542. _EUMPConfig_set(win.EUMPConfig);
  2543. Object.defineProperty(win, 'EUMPConfig', {
  2544. enumerable: true,
  2545. get: () => _EUMPConfig,
  2546. set: _EUMPConfig_set
  2547. });
  2548. }, nullTools)
  2549. };
  2550.  
  2551. scripts['24smi.org'] = () => selectiveCookies('has_adblock');
  2552.  
  2553. scripts['2picsun.ru'] = {
  2554. other: [
  2555. 'pics2sun.ru', '3pics-img.ru'
  2556. ],
  2557. now: () => {
  2558. Object.defineProperty(navigator, 'userAgent', {value: 'googlebot'});
  2559. }
  2560. };
  2561.  
  2562. scripts['4pda.ru'] = {
  2563. now: () => {
  2564. // https://greasyfork.org/en/scripts/14470-4pda-unbrender
  2565. let isForum = location.pathname.startsWith('/forum/'),
  2566. remove = node => (node && node.parentNode.removeChild(node)),
  2567. hide = node => (node && (node.style.display = 'none'));
  2568.  
  2569. // clean a page
  2570. window.addEventListener(
  2571. 'DOMContentLoaded', function() {
  2572. let width = () => window.innerWidth || _de.clientWidth || _document.body.clientWidth || 0;
  2573. let height = () => window.innerHeight || _de.clientHeight || _document.body.clientHeight || 0;
  2574.  
  2575. HeaderAds: {
  2576. // hide ads above HEADER
  2577. let nav = _document.querySelector('.menu');
  2578. if (!nav) {
  2579. _console.warn('Unable to locate header element');
  2580. break HeaderAds;
  2581. }
  2582. for (let itm of nav.parentNode.children)
  2583. if (itm !== nav)
  2584. hide(itm);
  2585. else break;
  2586. }
  2587.  
  2588. if (isForum) {
  2589. let itm = _document.querySelector('#logostrip');
  2590. if (itm)
  2591. remove(itm.parentNode.nextSibling);
  2592. // clear background in the download frame
  2593. if (location.pathname.startsWith('/forum/dl/')) {
  2594. let setBackground = node => _setAttribute(
  2595. node,
  2596. 'style', (_getAttribute(node, 'style') || '') +
  2597. ';background-color:#4ebaf6!important'
  2598. );
  2599. setBackground(_document.body);
  2600. for (let itm of _document.querySelectorAll('body > div'))
  2601. if (!itm.querySelector('.dw-fdwlink, .content') && !itm.classList.contains('footer'))
  2602. remove(itm);
  2603. else
  2604. setBackground(itm);
  2605. }
  2606. // exist from DOMContentLoaded since the rest is not for forum
  2607. return;
  2608. }
  2609.  
  2610. FixNavMenu: {
  2611. // hide ad link from the navigation
  2612. let ad = _document.querySelector('.menu-main-item > a > svg');
  2613. if (!ad) {
  2614. _console.warn('Unable to locate menu ad item');
  2615. break FixNavMenu;
  2616. } else {
  2617. ad = ad.parentNode.parentNode;
  2618. hide(ad);
  2619. }
  2620. }
  2621. SidebarAds: {
  2622. // remove ads from sidebar
  2623. let aside = _document.querySelectorAll('[class]:not([id]) > [id]:not([class]) > :first-child + :last-child:not(.v-panel)');
  2624. if (!aside.length) {
  2625. _console.warn('Unable to locate sidebar');
  2626. break SidebarAds;
  2627. }
  2628. let post;
  2629. for (let side of aside) {
  2630. _console.log('Processing potential sidebar:', side);
  2631. for (let itm of Array.from(side.children)) {
  2632. post = itm.classList.contains('post');
  2633. if (itm.querySelector('iframe') && !post)
  2634. remove(itm);
  2635. if (itm.querySelector('script, a[target="_blank"] > img') && !post || !itm.children.length)
  2636. hide(itm);
  2637. }
  2638. }
  2639. }
  2640.  
  2641. _document.body.setAttribute('style', (_document.body.getAttribute('style')||'')+';background-color:#E6E7E9!important');
  2642.  
  2643. let extra = 'background-image:none!important;background-color:transparent!important',
  2644. fakeStyles = new WeakMap(),
  2645. styleProxy = {
  2646. get: (target, prop) => fakeStyles.get(target)[prop] || target[prop],
  2647. set: function(target, prop, value) {
  2648. let fakeStyle = fakeStyles.get(target);
  2649. ((prop in fakeStyle) ? fakeStyle : target)[prop] = value;
  2650. return true;
  2651. }
  2652. };
  2653. for (let itm of _document.querySelectorAll('[id]:not(A), A')) {
  2654. if (!(itm.offsetWidth > 0.95 * width() &&
  2655. itm.offsetHeight > 0.85 * height()))
  2656. continue;
  2657. if (itm.tagName !== 'A') {
  2658. fakeStyles.set(itm.style, {
  2659. 'backgroundImage': itm.style.backgroundImage,
  2660. 'backgroundColor': itm.style.backgroundColor
  2661. });
  2662.  
  2663. try {
  2664. Object.defineProperty(itm, 'style', {
  2665. value: new Proxy(itm.style, styleProxy),
  2666. enumerable: true
  2667. });
  2668. } catch (e) {
  2669. _console.log('Unable to protect style property.', e);
  2670. }
  2671.  
  2672. _setAttribute(itm, 'style', `${(_getAttribute(itm, 'style') || '')};${extra}`);
  2673. }
  2674. if (itm.tagName === 'A')
  2675. _setAttribute(itm, 'style', 'display:none!important');
  2676. }
  2677. }
  2678. );
  2679. }
  2680. };
  2681.  
  2682. scripts['adhands.ru'] = () => scriptLander(() => {
  2683. let nt = new nullTools();
  2684. try {
  2685. let _adv;
  2686. Object.defineProperty(win, 'adv', {
  2687. get: () => _adv,
  2688. set: (v) => {
  2689. _console.log('Blocked advert on adhands.ru.');
  2690. nt.define(v, 'advert', '');
  2691. _adv = v;
  2692. }
  2693. });
  2694. } catch (ignore) {
  2695. if (!win.adv)
  2696. _console.log('Unable to locate advert on adhands.ru.');
  2697. else {
  2698. _console.log('Blocked advert on adhands.ru.');
  2699. nt.define(win.adv, 'advert', '');
  2700. }
  2701. }
  2702. }, nullTools);
  2703.  
  2704. scripts['all-episodes.tv'] = () => {
  2705. let nt = new nullTools();
  2706. nt.define(win, 'perX1', 2);
  2707. createStyle('#advtss, #ad3, a[href*="/ad.admitad.com/"] { display:none!important }');
  2708. };
  2709.  
  2710. scripts['allhentai.ru'] = () => {
  2711. selectiveEval();
  2712. preventPopups();
  2713. scriptLander(() => {
  2714. let _onerror = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onerror');
  2715. if (!_onerror)
  2716. return;
  2717. _onerror.set = (...args) => _console.log(args[0].toString());
  2718. Object.defineProperty(HTMLElement.prototype, 'onerror', _onerror);
  2719. });
  2720. };
  2721.  
  2722. scripts['allmovie.pro'] = {
  2723. other: ['rufilmtv.org'],
  2724. dom: function() {
  2725. // pretend to be Android to make site use different played for ads
  2726. if (isSafari)
  2727. return;
  2728. Object.defineProperty(navigator, 'userAgent', {
  2729. get: function(){
  2730. 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';
  2731. },
  2732. enumerable: true
  2733. });
  2734. }
  2735. };
  2736.  
  2737. scripts['anidub-online.ru'] = {
  2738. other: ['anime.anidub.com', 'online.anidub.com'],
  2739. dom: function() {
  2740. if (win.ogonekstart1)
  2741. win.ogonekstart1 = () => _console.log("Fire in the hole!");
  2742. },
  2743. now: () => createStyle([
  2744. '.background {background: none!important;}',
  2745. '.background > script + div,'+
  2746. '.background > script ~ div:not([id]):not([class]) + div[id][class]'+
  2747. '{display:none!important}'
  2748. ])
  2749. };
  2750.  
  2751. scripts['tv.animebest.org'] = {
  2752. now: () => {
  2753. let _eval = win.eval;
  2754. win.eval = new win.Proxy(win.eval, {
  2755. apply: (evl, ths, args) => {
  2756. if (typeof args[0] === 'string' &&
  2757. args[0].includes("'VASTP'")) {
  2758. args[0] = args[0].replace("'VASTP'", "''");
  2759. win.eval = _eval;
  2760. }
  2761. return Reflect.apply(evl, ths, args);
  2762. }
  2763. });
  2764. }
  2765. };
  2766.  
  2767. scripts['audioportal.su'] = {
  2768. now: () => createStyle('#blink2 { display: none !important }'),
  2769. dom: () => {
  2770. let links = _document.querySelectorAll('a[onclick*="clickme("]');
  2771. if (!links) return;
  2772. for (let link of links)
  2773. clickme(link);
  2774. }
  2775. };
  2776.  
  2777. scripts['avito.ru'] = () => selectiveCookies('abp|cmtchd|crookie|is_adblock');
  2778.  
  2779. scripts['di.fm'] = () => scriptLander(() => {
  2780. let log = false;
  2781. // wrap global app object to catch registration of specific modules
  2782. let _di = void 0;
  2783. Object.defineProperty(win, 'di', {
  2784. get: () => _di,
  2785. set: vl => {
  2786. if (vl === _di)
  2787. return;
  2788. log && _console.log('di =', vl);
  2789. _di = new Proxy(vl, {
  2790. set: (di, name, vl) => {
  2791. if (vl === di[name])
  2792. return true;
  2793. if (name === 'app') {
  2794. log && _console.log('di.app =', vl);
  2795. if ('module' in vl)
  2796. vl.module = new Proxy(vl.module, {
  2797. apply: (module, that, args) => {
  2798. if (/Wall|Banner|Detect|WebplayerApp\.Ads/.test(args[0])) {
  2799. let name = args[0];
  2800. log && _console.warn('wrap', name, 'module');
  2801. if (typeof args[1] === 'function')
  2802. args[1] = new Proxy(args[1], {
  2803. apply: (fun, that, args) => {
  2804. if (args[0]) // module object
  2805. args[0].start = () => _console.log('Skipped start of', name);
  2806. return Reflect.apply(fun, that, args);
  2807. }
  2808. });
  2809. }// else log && _console.log('loading module', args[0]);
  2810. if (args[0] === 'Modals') {
  2811. log && _console.warn('wrap', name, 'module');
  2812. if (typeof args[1] === 'function')
  2813. args[1] = new Proxy(args[1], {
  2814. apply: (fun, that, args) => {
  2815. if ('commands' in args[1] && 'setHandlers' in args[1].commands &&
  2816. !Object.hasOwnProperty.call(args[1].commands, 'setHandlers')) {
  2817. let _commands = args[1].commands;
  2818. _commands.setHandlers = new Proxy(_commands.setHandlers, {
  2819. apply: (fun, that, args) => {
  2820. for (let name in args[0])
  2821. if (name === 'modal:streaminterrupt' ||
  2822. name === 'modal:midroll')
  2823. args[0][name] = () => _console.log('Skipped', name, 'window');
  2824. delete _commands.setHandlers;
  2825. return Reflect.apply(fun, that, args);
  2826. }
  2827. });
  2828. }
  2829. return Reflect.apply(fun, that, args);
  2830. }
  2831. });
  2832. }
  2833. return Reflect.apply(module, that, args);
  2834. }
  2835. });
  2836. }
  2837. di[name] = vl;
  2838. return true;
  2839. }
  2840. });
  2841. }
  2842. });
  2843. // don't send errorception logs
  2844. Object.defineProperty(win, 'onerror', {
  2845. set: vl => log && _console.warn('Skipped global onerror callback', vl)
  2846. });
  2847. });
  2848.  
  2849. scripts['draug.ru'] = {
  2850. other: ['vargr.ru'],
  2851. now: () => scriptLander(() => {
  2852. if (location.pathname === '/pop.html')
  2853. win.close();
  2854. createStyle([
  2855. '#timer_1 { display: none !important }',
  2856. '#timer_2 { display: block !important }'
  2857. ]);
  2858. let _contentWindow = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, 'contentWindow');
  2859. let _get_contentWindow = Function.prototype.apply.bind(_contentWindow.get);
  2860. _contentWindow.get = function() {
  2861. let res = _get_contentWindow(this);
  2862. if (res.location.href === 'about:blank')
  2863. res.document.write = (...args) => _console.log('Skipped iframe.write(', ...args, ')');
  2864. return res;
  2865. };
  2866. Object.defineProperty(HTMLIFrameElement.prototype, 'contentWindow', _contentWindow);
  2867. }),
  2868. dom: () => {
  2869. let list = _querySelectorAll('div[id^="yandex_rtb_"], .adsbygoogle');
  2870. list.forEach(node => _console.log('Removed:', node.parentNode.parentNode.removeChild(node.parentNode)));
  2871. }
  2872. };
  2873.  
  2874. scripts['drive2.ru'] = () => {
  2875. selectiveCookies();
  2876. gardener('.c-block:not([data-metrika="recomm"]),.o-grid__item', />Реклама<\//i);
  2877. scriptLander(() => {
  2878. let _d2 = void 0;
  2879. Object.defineProperty(win, 'd2', {
  2880. get: () => _d2,
  2881. set: o => {
  2882. if (o === _d2)
  2883. return true;
  2884. _d2 = new Proxy(o, {
  2885. set: (tgt, prop, val) => {
  2886. if (['brandingRender', 'dvReveal', '__dv'].includes(prop))
  2887. val = () => null;
  2888. tgt[prop] = val;
  2889. return true;
  2890. }
  2891. });
  2892. }
  2893. });
  2894. let nt = new nullTools();
  2895. nt.define(Object.prototype, 'initYaDirect', void 0, false);
  2896. }, nullTools);
  2897. };
  2898.  
  2899. scripts['echo.msk.ru'] = () => {
  2900. selectiveCookies();
  2901. selectiveEval(evalPatternYandex, /^document\.write/, /callAdblock/);
  2902. }
  2903.  
  2904. scripts['fastpic.ru'] = () => {
  2905. let nt = new nullTools();
  2906. // Had to obfuscate property name to avoid triggering anti-obfuscation on greasyfork.org -_- (Exception 403012)
  2907. nt.define(win, `_0x${'4955'}`, []);
  2908. };
  2909.  
  2910. scripts['fishki.net'] = () => {
  2911. scriptLander(() => {
  2912. let nt = new nullTools();
  2913. let fishki = {};
  2914. nt.define(fishki, 'adv', nt.proxy({
  2915. afterAdblockCheck: nt.func(null),
  2916. refreshFloat: nt.func(null)
  2917. }));
  2918. nt.define(fishki, 'is_adblock', false);
  2919. nt.define(win, 'fishki', fishki);
  2920. }, nullTools);
  2921. gardener('.drag_list > .drag_element, .list-view > .paddingtop15, .post-wrap', /543769|Новости\sпартнеров|Полезная\sреклама/);
  2922. };
  2923.  
  2924. scripts['friends.in.ua'] = () => scriptLander(() => {
  2925. Object.defineProperty(win, 'need_warning', {
  2926. get: () => 0, set: () => null
  2927. });
  2928. });
  2929.  
  2930. scripts['gidonline.club'] = () => createStyle('.tray > div[style] {display: none!important}');
  2931.  
  2932. scripts['hdgo.cc'] = {
  2933. other: ['46.30.43.38', 'couber.be'],
  2934. now: () => (new MutationObserver(
  2935. (ms) => {
  2936. let m, node;
  2937. for (m of ms) for (node of m.addedNodes)
  2938. if (node.tagName instanceof HTMLScriptElement && _getAttribute(node, 'onerror') !== null)
  2939. node.removeAttribute('onerror');
  2940. }
  2941. )).observe(_document.documentElement, { childList:true, subtree: true })
  2942. };
  2943.  
  2944. scripts['gismeteo.ru'] = {
  2945. other: ['gismeteo.by', 'gismeteo.kz', 'gismeteo.ua'],
  2946. now: () => {
  2947. selectiveCookies('ab_[^=]*|redirect|_gab');
  2948. gardener('div > script', /AdvManager/i, { observe: true, parent: 'div' })
  2949. }
  2950. };
  2951.  
  2952. scripts['hdrezka.ag'] = () => {
  2953. Object.defineProperty(win, 'ab', { value: false, enumerable: true });
  2954. gardener('div[id][onclick][onmouseup][onmousedown]', /onmouseout/i);
  2955. };
  2956.  
  2957. scripts['hqq.tv'] = () => scriptLander(() => {
  2958. // disable anti-debugging in hqq.tv player
  2959. 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);
  2960. deepWrapAPI(root => {
  2961. // skip obfuscated stuff and a few other calls
  2962. let _setInterval = root.setInterval,
  2963. _setTimeout = root.setTimeout,
  2964. _toString = root.Function.prototype.call.bind(root.Function.prototype.toString);
  2965. root.setInterval = (...args) => {
  2966. let fun = args[0];
  2967. if (fun instanceof Function) {
  2968. let text = _toString(fun),
  2969. skip = text.includes('check();') || isObfuscated(text);
  2970. _console.warn('setInterval', text, 'skip', skip);
  2971. if (skip) return -1;
  2972. }
  2973. return _setInterval.apply(this, args);
  2974. };
  2975. let wrappedST = new WeakSet();
  2976. root.setTimeout = (...args) => {
  2977. let fun = args[0];
  2978. if (fun instanceof Function) {
  2979. let text = _toString(fun),
  2980. skip = fun.name === 'check' || isObfuscated(text);
  2981. if (!wrappedST.has(fun)) {
  2982. _console.warn('setTimeout', text, 'skip', skip);
  2983. wrappedST.add(fun);
  2984. }
  2985. if (skip) return;
  2986. }
  2987. return _setTimeout.apply(this, args);
  2988. };
  2989. // skip 'debugger' call
  2990. let _eval = root.eval;
  2991. root.eval = text => {
  2992. if (typeof text === 'string' && text.includes('debugger;')) {
  2993. _console.warn('skip eval', text);
  2994. return;
  2995. }
  2996. _eval(text);
  2997. };
  2998. // Prevent RegExpt + toString trick
  2999. let _proto = void 0;
  3000. try {
  3001. _proto = root.RegExp.prototype;
  3002. } catch(ignore) {
  3003. return;
  3004. }
  3005. let _RE_tS = Object.getOwnPropertyDescriptor(_proto, 'toString');
  3006. let _RE_tSV = _RE_tS.value || _RE_tS.get();
  3007. Object.defineProperty(_proto, 'toString', {
  3008. enumerable: _RE_tS.enumerable,
  3009. configurable: _RE_tS.configurable,
  3010. get: () => _RE_tSV,
  3011. set: val => _console.warn('Attempt to change toString for', this, 'with', _toString(val))
  3012. });
  3013. });
  3014. }, deepWrapAPI);
  3015.  
  3016. scripts['hideip.me'] = {
  3017. now: () => scriptLander(() => {
  3018. let _innerHTML = Object.getOwnPropertyDescriptor(_Element, 'innerHTML');
  3019. let _set_innerHTML = _innerHTML.set;
  3020. let _innerText = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'innerText');
  3021. let _get_innerText = _innerText.get;
  3022. let div = _document.createElement('div');
  3023. _innerHTML.set = function(...args) {
  3024. _set_innerHTML.call(div, args[0].replace('i','a'));
  3025. if (args[0] && /[рp][еe]кл/.test(_get_innerText.call(div))||
  3026. /(\d\d\d?\.){3}\d\d\d?:\d/.test(_get_innerText.call(this)) ) {
  3027. _console.log('Anti-Adblock killed.');
  3028. return true;
  3029. }
  3030. _set_innerHTML.apply(this, args);
  3031. };
  3032. Object.defineProperty(_Element, 'innerHTML', _innerHTML);
  3033. Object.defineProperty(win, 'adblock', {
  3034. get: () => false,
  3035. set: () => null,
  3036. enumerable: true
  3037. });
  3038. let _$ = {};
  3039. let _$_map = new WeakMap();
  3040. let _gOPD = Object.getOwnPropertyDescriptor(Object, 'getOwnPropertyDescriptor');
  3041. let _val_gOPD = _gOPD.value;
  3042. _gOPD.value = function(...args) {
  3043. let _res = _val_gOPD.apply(this, args);
  3044. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery')) {
  3045. delete _res.get;
  3046. delete _res.set;
  3047. _res.value = win[args[1]];
  3048. }
  3049. return _res;
  3050. };
  3051. Object.defineProperty(Object, 'getOwnPropertyDescriptor', _gOPD);
  3052. let getJQWrap = (n) => {
  3053. let name = n;
  3054. return {
  3055. enumerable: true,
  3056. get: () => _$[name],
  3057. set: x => {
  3058. if (_$_map.has(x)) {
  3059. _$[name] = _$_map.get(x);
  3060. return true;
  3061. }
  3062. if (x === _$.$ || x === _$.jQuery) {
  3063. _$[name] = x;
  3064. return true;
  3065. }
  3066. _$[name] = new Proxy(x, {
  3067. apply: (t, o, args) => {
  3068. let _res = t.apply(o, args);
  3069. if (_$_map.has(_res.is))
  3070. _res.is = _$_map.get(_res.is);
  3071. else {
  3072. let _is = _res.is;
  3073. _res.is = function(...args) {
  3074. if (args[0] === ':hidden')
  3075. return false;
  3076. return _is.apply(this, args);
  3077. };
  3078. _$_map.set(_is, _res.is);
  3079. }
  3080. return _res;
  3081. }
  3082. });
  3083. _$_map.set(x, _$[name]);
  3084. return true;
  3085. }
  3086. };
  3087. };
  3088. Object.defineProperty(win, '$', getJQWrap('$'));
  3089. Object.defineProperty(win, 'jQuery', getJQWrap('jQuery'));
  3090. let _dP = Object.defineProperty;
  3091. Object.defineProperty = function(...args) {
  3092. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery'))
  3093. return void 0;
  3094. return _dP.apply(this, args);
  3095. };
  3096. })
  3097. };
  3098.  
  3099. scripts['igra-prestoloff.cx'] = () => scriptLander(() => {
  3100. let nt = new nullTools();
  3101. /*jslint evil: true */ // yes, evil, I know
  3102. let _write = _document.write.bind(_document);
  3103. /*jslint evil: false */
  3104. nt.define(_document, 'write', t => {
  3105. let id = t.match(/jwplayer\("(\w+)"\)/i);
  3106. if (id && id[1])
  3107. return _write(`<div id="${id[1]}"></div>${t}`);
  3108. return _write('');
  3109. });
  3110. });
  3111.  
  3112. scripts['imageban.ru'] = () => { Object.defineProperty(win, 'V7x1J', { get: () => null }); };
  3113.  
  3114. scripts['inoreader.com'] = () => scriptLander(() => {
  3115. let i = setInterval(() => {
  3116. if ('adb_detected' in win) {
  3117. win.adb_detected = () => adb_not_detected();
  3118. clearInterval(i);
  3119. }
  3120. }, 10);
  3121. _document.addEventListener('DOMContentLoaded', () => clearInterval(i), false);
  3122. });
  3123.  
  3124. scripts['ivi.ru'] = () => {
  3125. let _xhr_open = win.XMLHttpRequest.prototype.open;
  3126. win.XMLHttpRequest.prototype.open = function(method, url, ...args) {
  3127. if (typeof url === 'string')
  3128. if (url.endsWith('/track'))
  3129. return;
  3130. return _xhr_open.call(this, method, url, ...args);
  3131. };
  3132. let _responseText = Object.getOwnPropertyDescriptor(XMLHttpRequest.prototype, 'responseText');
  3133. let _responseText_get = _responseText.get;
  3134. _responseText.get = function() {
  3135. if (this.__responseText__)
  3136. return this.__responseText__;
  3137. let res = _responseText_get.apply(this, arguments);
  3138. let o;
  3139. try {
  3140. if (res)
  3141. o = JSON.parse(res);
  3142. } catch(ignore) {};
  3143. let changed = false;
  3144. if (o && o.result) {
  3145. if (o.result instanceof Array &&
  3146. 'adv_network_logo_url' in o.result[0]) {
  3147. o.result = [];
  3148. changed = true;
  3149. }
  3150. if (o.result.show_adv) {
  3151. o.result.show_adv = false;
  3152. changed = true;
  3153. }
  3154. }
  3155. if (changed) {
  3156. _console.log('changed response >>', o);
  3157. res = JSON.stringify(o);
  3158. }
  3159. this.__responseText__ = res;
  3160. return res;
  3161. };
  3162. Object.defineProperty(XMLHttpRequest.prototype, 'responseText', _responseText);
  3163. };
  3164.  
  3165. scripts['kinopoisk.ru'] = () => {
  3166. selectiveCookies('cmtchd|crookie|kpunk');
  3167. // set no-branding body style and adjust other blocks on the page
  3168. let style = [
  3169. '.app__header.app__header_margin-bottom_brand, #top { margin-bottom: 20px !important }',
  3170. '.app__branding { display: none !important}'
  3171. ];
  3172. if (location.hostname === 'www.kinopoisk.ru' && !location.pathname.startsWith('/games/'))
  3173. style.push('html:not(#id), body:not(#id), .app-container { background: #d5d5d5 url(/images/noBrandBg.jpg) 50% 0 no-repeat !important }');
  3174. createStyle(style);
  3175. // catch branding and other things
  3176. let _KP = void 0;
  3177. Object.defineProperty(win, 'KP', {
  3178. get: () => _KP,
  3179. set: val => {
  3180. if (_KP === val)
  3181. return true;
  3182. _KP = new Proxy(val, {
  3183. set: (kp, name, val) => {
  3184. if (name === 'branding') {
  3185. kp[name] = new Proxy({ weborama: {} }, {
  3186. get: (kp, name) => name in kp ? kp[name] : '',
  3187. set: () => true
  3188. });
  3189. return true;
  3190. }
  3191. if (name === 'config')
  3192. val = new Proxy(val, {
  3193. set: (cfg, name, val) => {
  3194. if (name === 'anContextUrl')
  3195. return true;
  3196. if (name === 'adfoxEnabled' || name === 'hasBranding')
  3197. val = false;
  3198. if (name === 'adfoxVideoAdUrls')
  3199. val = {flash:{}, html:{}};
  3200. cfg[name] = val;
  3201. return true;
  3202. }
  3203. });
  3204. kp[name] = val;
  3205. return true;
  3206. }
  3207. });
  3208. _console.log('KP =', val);
  3209. }
  3210. });
  3211. // skip branding and some other junk
  3212. if (!('advBlock' in win))
  3213. Object.defineProperty(win, 'advBlock', {
  3214. get: () => () => null,
  3215. set: () => true
  3216. });
  3217. // skip timeout check for blocked requests
  3218. let _setTimeout = Function.prototype.apply.bind(win.setTimeout);
  3219. let _toString = Function.prototype.apply.bind(Function.prototype.toString);
  3220. win.setTimeout = function(...args) {
  3221. if (args[1] === 100) {
  3222. let str = _toString(args[0]);
  3223. if (str.endsWith('{a()}') || str.endsWith('{n()}'))
  3224. return;
  3225. }
  3226. return _setTimeout(this, args);
  3227. };
  3228. };
  3229.  
  3230. scripts['korrespondent.net'] = {
  3231. now: () => scriptLander(() => {
  3232. let nt = new nullTools();
  3233. nt.define(win, 'holder', function(id) {
  3234. let div = _document.getElementById(id);
  3235. if (!div)
  3236. return;
  3237. if (div.parentNode.classList.contains('col__sidebar')) {
  3238. div.parentNode.appendChild(div);
  3239. div.style.height = '300px';
  3240. }
  3241. });
  3242. }, nullTools),
  3243. dom: () => {
  3244. for (let frame of _document.querySelectorAll('.unit-side-informer > iframe'))
  3245. frame.parentNode.style.width = '1px';
  3246. }
  3247. };
  3248.  
  3249. scripts['liveinternet.ru'] = () => {
  3250. selectiveEval(evalPatternYandex);
  3251. selectiveCookies('bltsr|blcrm');
  3252. };
  3253.  
  3254. scripts['livejournal.com'] = () => scriptLander(() => {
  3255. let nt = new nullTools({log: true});
  3256. nt.define(win.Object.prototype, 'Adf', void 0, false);
  3257. }, nullTools);
  3258.  
  3259. scripts['mail.ru'] = {
  3260. other: ['ok.ru', 'sportmail.ru'],
  3261. now: () => {
  3262. selectiveCookies('act|testcookie');
  3263. scriptLander(() => {
  3264. let _hostparts = location.hostname.split('.');
  3265. let _subdomain = _hostparts.slice(-3).join('.');
  3266. let _hostname = _hostparts.slice(-2).join('.');
  3267. let _emailru = _subdomain === 'e.mail.ru' || _subdomain === 'octavius.mail.ru';
  3268. // setTimeout filter
  3269. let pattern = /advBlock|rbParams/i;
  3270. let _toString = Function.prototype.call.bind(Function.prototype.toString);
  3271. let _setTimeout = Function.prototype.apply.bind(win.setTimeout);
  3272. win.setTimeout = function setTimeout(...args) {
  3273. let text = _toString(args[0]);
  3274. if (pattern.test(text)) {
  3275. _console.warn('Skipped setTimeout:', text);
  3276. return;
  3277. }// else if (!text.includes('checkLoaded()'))
  3278. // _console.warn(text, args[1]);
  3279. return _setTimeout(this, args);
  3280. };
  3281.  
  3282. let nt = new nullTools();
  3283. // Trick to prevent mail.ru from removing 3rd-party styles
  3284. nt.define(win.Object.prototype, 'restoreVisibility', nt.func(null), false);
  3285. // Other Yandex Direct and other ads
  3286. nt.define(win.Object.prototype, 'initMimic', void 0, false);
  3287. nt.define(win.Object.prototype, 'hpConfig', void 0, false);
  3288. nt.define(win.Object.prototype, 'direct', void 0, false);
  3289. nt.define(win.Object.prototype, 'getAds', void 0, false);
  3290. if (_hostname === 'mail.ru') {
  3291. if (_subdomain === _hostname)
  3292. nt.define(win.Object.prototype, 'baits', void 0, false);
  3293. if (!_emailru) {
  3294. nt.define(win.Object.prototype, 'mimic', void 0, false);
  3295. nt.define(win, 'createRadar', nt.func(nt.func(null, 'aRadar'), 'createRadar'));
  3296. } else nt.define(win, 'aRadar', nt.func(null, 'aRadar'));
  3297. }
  3298. // banners on ok.ru and another counter
  3299. nt.define(win, 'getAdvTargetParam', nt.func(null, 'getAdvTargetParam'));
  3300. nt.define(win, 'rb_bannerClick', nt.func(null, 'rb_bannerClick'));
  3301. nt.define(win, 'rb_banner', nt.func(null, 'rb_banner'));
  3302. nt.define(win, 'rb_tadq', nt.func(null, 'rb_tadq'));
  3303. nt.define(win, 'rb_counter', nt.func(null, 'rb_counter'));
  3304. // shenanigans against ok.ru ABP detector
  3305. if (_hostname === 'ok.ru') {
  3306. createStyle('body > div:not([id]):not([class]) > .exit-popup {display: block !important}');
  3307. Object.defineProperty(win, 'mailruEnabled', {
  3308. get: () => undefined,
  3309. set: () => { return undefined.mailruEnabled; }
  3310. });
  3311. }
  3312. // all the rest is only needed on main page and in emails
  3313. if (_subdomain !== 'mail.ru' && !_emailru/* && _hostname !== 'ok.ru'*/)
  3314. return;
  3315.  
  3316. // Disable page scrambler on mail.ru to let extensions easily block ads there
  3317. let logger = {
  3318. apply: (target, thisArg, args) => {
  3319. let res = target.apply(thisArg, args);
  3320. _console.log(`${target._name}(`, ...args, `)\n>>`, res);
  3321. return res;
  3322. }
  3323. };
  3324.  
  3325. function wrapLocator(locator) {
  3326. if ('setup' in locator) {
  3327. let _setup = locator.setup;
  3328. locator.setup = function(o) {
  3329. if ('enable' in o) {
  3330. o.enable = false;
  3331. _console.log('Disable mimic mode.');
  3332. }
  3333. if ('links' in o) {
  3334. o.links = [];
  3335. _console.log('Call with empty list of sheets.');
  3336. }
  3337. return _setup.call(this, o);
  3338. };
  3339. locator.insertSheet = () => false;
  3340. locator.wrap = () => false;
  3341. }
  3342. try {
  3343. let names = [];
  3344. for (let name in locator)
  3345. if (locator[name] instanceof Function && name !== 'transform') {
  3346. locator[name]._name = "locator." + name;
  3347. locator[name] = new Proxy(locator[name], logger);
  3348. names.push(name);
  3349. }
  3350. _console.log(`[locator] wrapped properties: ${names.length ? names.join(', ') : '[empty]'}`);
  3351. } catch(e) {
  3352. _console.log(e);
  3353. }
  3354. return locator;
  3355. }
  3356.  
  3357. function defineLocator(root) {
  3358. let _locator = root.locator;
  3359. let wrapLocatorSetter = vl => _locator = wrapLocator(vl);
  3360. let loc_desc = Object.getOwnPropertyDescriptor(root, 'locator');
  3361. if (!loc_desc || loc_desc.set !== wrapLocatorSetter)
  3362. try {
  3363. Object.defineProperty(root, 'locator', {
  3364. set: wrapLocatorSetter,
  3365. get: () => _locator
  3366. });
  3367. } catch (err) {
  3368. _console.log('Unable to redefine "locator" object!!!', err);
  3369. }
  3370. if (loc_desc.value)
  3371. _locator = wrapLocator(loc_desc.value);
  3372. }
  3373.  
  3374. {
  3375. let missingCheck = {
  3376. get: (obj, name) => {
  3377. if (!(name in obj))
  3378. _console.warn(obj, 'missing:', name);
  3379. return obj[name];
  3380. }
  3381. };
  3382. // wow, Mail.ru can't just keep base Array functionality alone >_<
  3383. let _reduce = Function.prototype.call.bind(Array.prototype.reduce);
  3384. let skipLog = (name, ret) => (...args) => (_console.log(`Skip ${name}(`, ...args, ')'), ret);
  3385. let createSkipLogObject = (baseName, list) => _reduce(
  3386. list,
  3387. (acc, cur) => (acc[cur] = skipLog(`${baseName}.${cur}`), acc),
  3388. {}
  3389. );
  3390. let _apply = Reflect.apply;
  3391. let redefiner = {
  3392. apply: (target, thisArg, args) => {
  3393. let res = void 0;
  3394. let warn = false;
  3395. let name = target._name;
  3396. if (name === 'mrg-smokescreen/Welter')
  3397. res = {
  3398. isWelter: () => true,
  3399. wrap: skipLog(`${name}.wrap`)
  3400. };
  3401. if (name === 'mrg-smokescreen/StyleSheets')
  3402. res = createSkipLogObject(name, ['update', 'remove', 'insert', 'setup']);
  3403. if (name === 'mrg-smokescreen/Honeypot')
  3404. res = {
  3405. check: (...args) => (_console.log(`${name}.check(`, ...args, ')'), new Promise(() => void 0)),
  3406. version: "-1"
  3407. }
  3408. /*
  3409. if (name.startsWith('OK/banners/'))
  3410. res = createSkipLogObject(name, ['activate', 'ready', 'detectAdBlock', 'onHooksReady']);
  3411. if (name === 'OK/Smokescreen')
  3412. res = {
  3413. getLocator: skipLog(`${name}.getLocator`, void 0),
  3414. getById: id => {
  3415. let e = _document.getElementById(id);
  3416. if (e && !e.logged) {
  3417. _console.log(`${name}.getById(`, id, ') >', e);
  3418. e.logged = true;
  3419. }
  3420. return e;
  3421. }
  3422. };
  3423. */
  3424. if (name === 'advert/adman/adman') {
  3425. res = createSkipLogObject(name, ['deleteRBParams', 'getBlock', 'hasBlocker', 'init', 'refresh', 'setForceMimic', 'setRBParams']);
  3426. let features = { siteZones: {}, slots: {} };
  3427. [
  3428. 'expId', 'siteId', 'mimicEndpoint', 'mimicPartnerId', 'immediateFetchTimeout', 'delayedFetchTimeout'
  3429. ].forEach(name => void (features[name] = null));
  3430. res.getFeatures = skipLog('advert/adman/adman.getFeatures', features);
  3431. }
  3432. if (res) {
  3433. Object.defineProperty(res, Symbol.toStringTag, {
  3434. get: () => `Skiplog object for ${name}`
  3435. });
  3436. Object.defineProperty(res, Symbol.toPrimitive, {
  3437. value: function(hint) {
  3438. if (hint === 'string')
  3439. return Object.prototype.toString.call(this);
  3440. return `[missing toPrimitive] ${name} ${hint}`;
  3441. }
  3442. });
  3443. res = new Proxy(res, missingCheck);
  3444. } else {
  3445. res = _apply(target, thisArg, args);
  3446. warn = true;
  3447. }
  3448. if (name === 'mrg-smokescreen/Utils')
  3449. res.extend = function(...args) {
  3450. let res = {
  3451. enable: false,
  3452. match: [],
  3453. links: []
  3454. };
  3455. _console.log(`${name}.extend(`, ...args, ') >>', res );
  3456. return res;
  3457. };
  3458. _console[warn?'warn':'log'](name, '(',...args,')\n>>', res);
  3459. return res;
  3460. }
  3461. };
  3462.  
  3463. let advModuleNamesStartWith = /^(mrg-(context|honeypot)|adv\/)/;
  3464. let advModuleNamesGeneric = /advert|banner|mimic|smoke/i;
  3465. let wrapAdFuncs = {
  3466. apply: (target, thisArg, args) => {
  3467. let module = args[0];
  3468. if (typeof module === 'string')
  3469. if ((advModuleNamesStartWith.test(module) ||
  3470. advModuleNamesGeneric.test(module)) &&
  3471. // fix for e.mail.ru in Fx56 and below, looks like Proxy is quirky there
  3472. !module.startsWith('patron.v2.')) {
  3473. let fun = args[args.length-1];
  3474. fun._name = module;
  3475. args[args.length-1] = new Proxy(fun, redefiner);
  3476. }
  3477. return _apply(target, thisArg, args);
  3478. }
  3479. };
  3480. let wrapDefine = def => {
  3481. if (!def)
  3482. return;
  3483. _console.log('define =', def);
  3484. def = new Proxy(def, wrapAdFuncs);
  3485. def._name = 'define';
  3486. return def;
  3487. };
  3488. let _define = wrapDefine(win.define);
  3489. Object.defineProperty(win, 'define', {
  3490. get: () => _define,
  3491. set: x => {
  3492. if (_define === x)
  3493. return true;
  3494. _define = wrapDefine(x);
  3495. return true;
  3496. }
  3497. });
  3498. }
  3499.  
  3500. let _honeyPot;
  3501. function defineDetector(mr) {
  3502. let __ = mr._ || {};
  3503. let setHoneyPot = o => {
  3504. if (!o || o === _honeyPot) return;
  3505. _console.log('[honeyPot]', o);
  3506. _honeyPot = function() {
  3507. this.check = new Proxy(() => {
  3508. __.STUCK_IN_POT = false;
  3509. return false;
  3510. }, logger);
  3511. this.check._name = 'honeyPot.check';
  3512. this.destroy = () => null;
  3513. };
  3514. };
  3515. if ('honeyPot' in mr)
  3516. setHoneyPot(mr.honeyPot);
  3517. else
  3518. Object.defineProperty(mr, 'honeyPot', {
  3519. get: () => _honeyPot,
  3520. set: setHoneyPot
  3521. });
  3522.  
  3523. __ = new Proxy(__, {
  3524. get: (t, p) => t[p],
  3525. set: (t, p, v) => {
  3526. _console.log(`mr._.${p} =`, v);
  3527. t[p] = v;
  3528. return true;
  3529. }
  3530. });
  3531. mr._ = __;
  3532. }
  3533.  
  3534. function defineAdd(mr) {
  3535. let _add;
  3536. let addWrapper = {
  3537. apply: (tgt, that, args) => {
  3538. let module = args[0];
  3539. if (typeof module === 'string' && module.startsWith('ad')) {
  3540. _console.log('Skip module:', module);
  3541. return;
  3542. }
  3543. if (typeof module === 'object' && module.name.startsWith('ad'))
  3544. _console.log('Loaded module:', module);
  3545. return logger.apply(tgt, that, args);
  3546. }
  3547. };
  3548. let setMrAdd = v => {
  3549. if (!v) return;
  3550. v._name = 'mr.add';
  3551. v = new Proxy(v, addWrapper);
  3552. _add = v;
  3553. };
  3554. if ('add' in mr)
  3555. setMrAdd(mr.add);
  3556. Object.defineProperty(mr, 'add', {
  3557. get: () => _add,
  3558. set: setMrAdd
  3559. });
  3560.  
  3561. }
  3562.  
  3563. let _mr_wrapper = vl => {
  3564. defineLocator(vl.mimic ? vl.mimic : vl);
  3565. defineDetector(vl);
  3566. defineAdd(vl);
  3567. return vl;
  3568. };
  3569. if ('mr' in win) {
  3570. _console.log('Found existing "mr" object.');
  3571. win.mr = _mr_wrapper(win.mr);
  3572. } else {
  3573. let _mr = void 0;
  3574. Object.defineProperty(win, 'mr', {
  3575. get: () => _mr,
  3576. set: vl => { _mr = _mr_wrapper(vl) },
  3577. configurable: true
  3578. });
  3579. let _defineProperty = Function.prototype.apply.bind(Object.defineProperty);
  3580. Object.defineProperty = function defineProperty(o, name, conf) {
  3581. if (name === 'mr' && o instanceof Window) {
  3582. _console.warn('Object.defineProperty(', ...arguments, ')');
  3583. conf.set(_mr_wrapper(conf.get()));
  3584. }
  3585. if ((name === 'honeyPot' || name === 'add') && _mr === o && conf.set)
  3586. return;
  3587. return _defineProperty(this, arguments);
  3588. };
  3589. }
  3590. }, nullTools);
  3591. }
  3592. };
  3593.  
  3594. scripts['oms.matchat.online'] = () => scriptLander(() => {
  3595. let _rmpGlobals = void 0;
  3596. Object.defineProperty(win, 'rmpGlobals', {
  3597. get: () => _rmpGlobals,
  3598. set: x => {
  3599. if (x === _rmpGlobals)
  3600. return true;
  3601. _rmpGlobals = new Proxy(x, {
  3602. get: (obj, name) => {
  3603. if (name === 'adBlockerDetected')
  3604. return false;
  3605. return obj[name];
  3606. },
  3607. set: (obj, name, val) => {
  3608. if (name === 'adBlockerDetected')
  3609. _console.warn('rmpGlobals.adBlockerDetected =', val)
  3610. else
  3611. obj[name] = val;
  3612. return true;
  3613. }
  3614. });
  3615. }
  3616. });
  3617. });
  3618.  
  3619. scripts['megogo.net'] = {
  3620. now: () => {
  3621. let nt = new nullTools();
  3622. nt.define(win, 'adBlock', false);
  3623. nt.define(win, 'showAdBlockMessage', nt.func(null));
  3624. }
  3625. };
  3626.  
  3627. scripts['n-torrents.org'] = () => scriptLander(() => {
  3628. let _$ = void 0;
  3629. Object.defineProperty(win, '$', {
  3630. get: () => _$,
  3631. set: vl => {
  3632. _$ = vl;
  3633. if (!vl.fn)
  3634. return true;
  3635. let _videoPopup = vl.fn.videoPopup;
  3636. Object.defineProperty(vl.fn, 'videoPopup', {
  3637. get: () => _videoPopup,
  3638. set: vl => {
  3639. if (vl === _videoPopup)
  3640. return true;
  3641. _videoPopup = new Proxy(vl, {
  3642. apply: (fun, obj, args) => {
  3643. let opts = args[0];
  3644. if (opts) {
  3645. opts.adv = '';
  3646. opts.duration = 0;
  3647. }
  3648. return Reflect.apply(fun, obj, args);
  3649. }
  3650. });
  3651. return true;
  3652. }
  3653. });
  3654. return true
  3655. }
  3656. });
  3657. });
  3658.  
  3659. scripts['naruto-base.su'] = () => gardener('div[id^="entryID"],.block', /href="http.*?target="_blank"/i);
  3660.  
  3661. scripts['newdeaf-online.net'] = {
  3662. dom: () => {
  3663. let adNodes = _document.querySelectorAll('.ads');
  3664. if (!adNodes)
  3665. return;
  3666. let getter = x => {
  3667. let val = x;
  3668. return () => (_console.warn('read .ads', name, val), val);
  3669. };
  3670. let setter = x => _console.warn('skip write .ads', name, x);
  3671. for (let adNode of adNodes)
  3672. for (let name of ['innerHTML'])
  3673. Object.defineProperty(adNode, name, {
  3674. get: getter(ads[name]),
  3675. set: setter
  3676. });
  3677. }
  3678. };
  3679.  
  3680. scripts['overclockers.ru'] = {
  3681. dom: () => scriptLander(() => {
  3682. let killed = () => _console.warn('Anti-Adblock killed.');
  3683. if ('$' in win)
  3684. win.$ = new Proxy($, {
  3685. apply: (tgt, that, args) => {
  3686. let res = tgt.apply(that, args);
  3687. if (res[0] && res[0] === _document.body) {
  3688. res.html = killed;
  3689. res.empty = killed;
  3690. }
  3691. return res;
  3692. }
  3693. });
  3694. })
  3695. };
  3696. scripts['forums.overclockers.ru'] = {
  3697. now: () => {
  3698. createStyle('.needblock {position: fixed; left: -10000px}');
  3699. Object.defineProperty(win, 'adblck', {
  3700. get: () => 'no',
  3701. set: () => undefined,
  3702. enumerable: true
  3703. });
  3704. }
  3705. };
  3706.  
  3707. scripts['pb.wtf'] = {
  3708. other: ['piratbit.org', 'piratbit.ru'],
  3709. dom: () => {
  3710. // line above topic content and images in the slider in the header
  3711. let remove = node => (_console.log('removed', node), node.parentNode.removeChild(node));
  3712. for (let el of _document.querySelectorAll('.release-block-img a, #page_content a')) {
  3713. if (location.hostname === el.hostname &&
  3714. /^\/(\w{3}|exit)\/[\w=/]{20,}$/.test(el.pathname)) {
  3715. remove(el.closest('div, tr'));
  3716. continue;
  3717. }
  3718. // ads in the topic header in case filter above wasn't enough
  3719. let parent = el.closest('tr');
  3720. if (parent) {
  3721. let span = (parent.querySelector('span') || {}).textContent;
  3722. span && span.startsWith('YO!') && remove(parent);
  3723. }
  3724. }
  3725. // casino ad button in random places
  3726. for (let el of _document.querySelectorAll('.btn-group')) {
  3727. el = el.parentNode;
  3728. if (el.tagName === 'CENTER')
  3729. remove(el.parentNode);
  3730. }
  3731. // ads in comments
  3732. let el = _document.querySelector('thead + tbody[id^="post_"] + tbody[class*=" "]');
  3733. if (el && el.parentNode.children[2] == el)
  3734. remove(el);
  3735. }
  3736. };
  3737.  
  3738. scripts['pikabu.ru'] = () => gardener('.story', /story__author[^>]+>ads</i, {root: '.inner_wrap', observe: true});
  3739.  
  3740. scripts['peka2.tv'] = () => {
  3741. let bodyClass = 'body--branding';
  3742. let checkNode = node => {
  3743. for (let className of node.classList)
  3744. if (className.includes('banner') || className === bodyClass) {
  3745. _removeAttribute(node, 'style');
  3746. node.classList.remove(className);
  3747. for (let attr of Array.from(node.attributes))
  3748. if (attr.name.startsWith('advert'))
  3749. _removeAttribute(node, attr.name);
  3750. }
  3751. };
  3752. (new MutationObserver(ms => {
  3753. let m, node;
  3754. for (m of ms) for (node of m.addedNodes)
  3755. if (node instanceof HTMLElement)
  3756. checkNode(node);
  3757. })).observe(_de, {childList: true, subtree: true});
  3758. (new MutationObserver(ms => {
  3759. for (let m of ms)
  3760. checkNode(m.target);
  3761. })).observe(_de, {attributes: true, subtree: true, attributeFilter: ['class']});
  3762. };
  3763.  
  3764. scripts['qrz.ru'] = {
  3765. now: () => {
  3766. let nt = new nullTools();
  3767. nt.define(win, 'ab', false);
  3768. nt.define(win, 'tryMessage', nt.func(null));
  3769. }
  3770. };
  3771.  
  3772. scripts['razlozhi.ru'] = {
  3773. now: () => {
  3774. let nt = new nullTools();
  3775. nt.define(win, 'cadb', false);
  3776. for (let func of ['createShadowRoot', 'attachShadow'])
  3777. if (func in _Element)
  3778. _Element[func] = function(){
  3779. return this.cloneNode();
  3780. };
  3781. }
  3782. };
  3783.  
  3784. scripts['rbc.ru'] = {
  3785. other: ['autonews.ru', 'rbcplus.ru', 'sportrbc.ru'],
  3786. now: () => {
  3787. selectiveCookies('adb_on');
  3788. let _RA = void 0;
  3789. let setArgs = {
  3790. 'showBanners': true,
  3791. 'showAds': true,
  3792. 'banners.staticPath': '',
  3793. 'paywall.staticPath': '',
  3794. 'banners.dfp.config': [],
  3795. 'banners.dfp.pageTargeting': () => null,
  3796. };
  3797. Object.defineProperty(win, 'RA', {
  3798. get: () => _RA,
  3799. set: vl => {
  3800. _console.log('RA =', vl);
  3801. if ('repo' in vl) {
  3802. _console.log('RA.repo =', vl.repo);
  3803. vl.repo = new Proxy(vl.repo, {
  3804. set: (o, name, val) => {
  3805. if (name === 'banner') {
  3806. _console.log(`RA.repo.${name} =`, val);
  3807. val = new Proxy(val, {
  3808. get: (o, name) => {
  3809. let res = o[name];
  3810. if (typeof o[name] === 'function') {
  3811. res = () => void 0;
  3812. if (name === 'getService')
  3813. res = service => {
  3814. if (service === 'dfp')
  3815. return {
  3816. getPlaces: () => void 0,
  3817. createPlaceholder: () => void 0
  3818. }
  3819. return void 0;
  3820. }
  3821. res.toString = o[name].toString.bind(o[name]);
  3822. }
  3823. if (name === 'isInited')
  3824. res = true;
  3825. _console.warn(`get RA.repo.banner.${name}`, res);
  3826. return res;
  3827. }
  3828. });
  3829. }
  3830. o[name] = val;
  3831. return true;
  3832. }
  3833. });
  3834. } else
  3835. _console.log('Unable to locate RA.repo');
  3836. _RA = new Proxy(vl, {
  3837. set: (o, name, val) => {
  3838. if (name === 'config') {
  3839. _console.log('RA.config =', val);
  3840. if ('set' in val) {
  3841. val.set = new Proxy(val.set, {
  3842. apply: (set, that, args) => {
  3843. let name = args[0];
  3844. if (name in setArgs)
  3845. args[1] = setArgs[name];
  3846. if (name in setArgs || name === 'checkad')
  3847. _console.log('RA.config.set(', ...args, ')');
  3848. return Reflect.apply(set, that, args);
  3849. }
  3850. });
  3851. val.set('showAds', true); // pretend ads already were shown
  3852. }
  3853. }
  3854. o[name] = val;
  3855. return true;
  3856. }
  3857. });
  3858. }
  3859. });
  3860. Object.defineProperty(win, 'bannersConfig', {
  3861. get: () => [], set: () => null
  3862. });
  3863. // pretend there is a paywall landing on screen already
  3864. let pwl = _document.createElement('div');
  3865. pwl.style.display = 'none';
  3866. pwl.className = 'js-paywall-landing';
  3867. _document.documentElement.appendChild(pwl);
  3868. // detect and skip execution of one of the ABP detectors
  3869. let _setTimeout = Function.prototype.apply.bind(win.setTimeout);
  3870. let _toString = Function.prototype.call.bind(Function.prototype.toString);
  3871. win.setTimeout = function setTimeout() {
  3872. if (typeof arguments[0] === 'function') {
  3873. let fts = _toString(arguments[0]);
  3874. if (/\.length\s*>\s*0\s*&&/.test(fts) && /:hidden/.test(fts)) {
  3875. _console.log('Skipped setTimout(', fts, arguments[1], ')');
  3876. return;
  3877. }
  3878. }
  3879. return _setTimeout(this, arguments);
  3880. };
  3881. // hide banner placeholders
  3882. createStyle('[data-banner-id], .banner__container, .banners__yandex__article { display: none !important }');
  3883. },
  3884. dom: () => {
  3885. // hide sticky banner place at the top of the page
  3886. for (let itm of _document.querySelectorAll('.l-sticky'))
  3887. if (itm.querySelector('.banner__container__link'))
  3888. itm.style.display = 'none';
  3889. }
  3890. };
  3891.  
  3892. scripts['rp5.ru'] = {
  3893. other: ['rp5.by', 'rp5.kz', 'rp5.ua'],
  3894. now: () => {
  3895. Object.defineProperty(win, 'sContentBottom', {
  3896. get: () => '',
  3897. set: () => true
  3898. });
  3899. // skip timeout check for blocked requests
  3900. let _setTimeout = Function.prototype.apply.bind(win.setTimeout);
  3901. let _toString = Function.prototype.apply.bind(Function.prototype.toString);
  3902. win.setTimeout = function(...args) {
  3903. let str = (typeof args[0] === 'string' ? args[0] : _toString(args[0]));
  3904. if (str.includes('xvb')) {
  3905. _console.log('Blocked setTimeout for:', str);
  3906. return;
  3907. }
  3908. return _setTimeout(this, args);
  3909. };
  3910. },
  3911. dom: () => {
  3912. let node = selectNodeByTextContent('Разместить текстовое объявление', { root: _de.querySelector('#content-wrapper'), shallow: true });
  3913. if (node)
  3914. node.style.display = 'none';
  3915. }
  3916. };
  3917.  
  3918. scripts['rutube.ru'] = () => scriptLander(() => {
  3919. let _parse = JSON.parse;
  3920. let _skip_enabled = false;
  3921. JSON.parse = (...args) => {
  3922. let res = _parse(...args),
  3923. log = false;
  3924. if (!res)
  3925. return res;
  3926. // parse player configuration
  3927. if ('appearance' in res || 'video_balancer' in res) {
  3928. log = true;
  3929. if (res.appearance) {
  3930. if ('forbid_seek' in res.appearance && res.appearance.forbid_seek)
  3931. res.appearance.forbid_seek = false;
  3932. if ('forbid_timeline_preview' in res.appearance && res.appearance.forbid_timeline_preview)
  3933. res.appearance.forbid_timeline_preview = false;
  3934. }
  3935. _skip_enabled = !!res.remove_unseekable_blocks;
  3936. //res.advert = [];
  3937. delete res.advert;
  3938. //for (let limit of res.limits)
  3939. // limit.limit = 0;
  3940. delete res.limits;
  3941. //res.yast = null;
  3942. //res.yast_live_online = null;
  3943. delete res.yast;
  3944. delete res.yast_live_online;
  3945. Object.defineProperty(res, 'stat', {
  3946. get: () => [],
  3947. set: () => true,
  3948. enumerable: true
  3949. });
  3950. }
  3951.  
  3952. // parse video configuration
  3953. if ('video_url' in res) {
  3954. log = true;
  3955. if (res.cuepoints && !_skip_enabled)
  3956. for (let point of res.cuepoints) {
  3957. point.is_pause = false;
  3958. point.show_navigation = true;
  3959. point.forbid_seek = false;
  3960. }
  3961. }
  3962.  
  3963. if (log)
  3964. _console.log('[rutube]', res);
  3965. return res;
  3966. };
  3967. });
  3968.  
  3969. scripts['simpsonsua.com.ua'] = {
  3970. other: ['simpsonsua.tv'],
  3971. now: () => scriptLander(() => {
  3972. let _addEventListener = _Document.addEventListener;
  3973. _document.addEventListener = function(event, callback) {
  3974. if (event === 'DOMContentLoaded' && callback.toString().includes('show_warning'))
  3975. return;
  3976. return _addEventListener.apply(this, arguments);
  3977. };
  3978. let nt = new nullTools();
  3979. nt.define(win, 'need_warning', 0);
  3980. }, nullTools)
  3981. };
  3982.  
  3983. scripts['smotretanime.ru'] = () => scriptLander(() => {
  3984. deepWrapAPI(root => {
  3985. let _pause = root.Function.prototype.call.bind(root.Audio.prototype.pause);
  3986. let _addEventListener = root.Function.prototype.call.bind(root.Element.prototype.addEventListener);
  3987. let stopper = e => _pause(e.target);
  3988. root.Audio = new Proxy(root.Audio, {
  3989. construct: (audio, args) => {
  3990. let res = new audio(...args);
  3991. _addEventListener(res, 'play', stopper, true);
  3992. return res;
  3993. }
  3994. });
  3995. _createElement = root.Document.prototype.createElement;
  3996. root.Document.prototype.createElement = function createElement() {
  3997. let res = _createElement.apply(this, arguments);
  3998. if (res instanceof HTMLAudioElement)
  3999. _addEventListener(res, 'play', stopper, true);
  4000. return res;
  4001. };
  4002. });
  4003. }, deepWrapAPI);
  4004.  
  4005. scripts['spaces.ru'] = () => {
  4006. gardener('div:not(.f-c_fll) > a[href*="spaces.ru/?Cl="]', /./, { parent: 'div' });
  4007. gardener('.js-banner_rotator', /./, { parent: '.widgets-group' });
  4008. };
  4009.  
  4010. scripts['spam-club.blogspot.co.uk'] = () => {
  4011. let _clientHeight = Object.getOwnPropertyDescriptor(_Element, 'clientHeight'),
  4012. _clientWidth = Object.getOwnPropertyDescriptor(_Element, 'clientWidth');
  4013. let wrapGetter = (getter) => {
  4014. let _getter = getter;
  4015. return function() {
  4016. let _size = _getter.apply(this, arguments);
  4017. return _size ? _size : 1;
  4018. };
  4019. };
  4020. _clientHeight.get = wrapGetter(_clientHeight.get);
  4021. _clientWidth.get = wrapGetter(_clientWidth.get);
  4022. Object.defineProperty(_Element, 'clientHeight', _clientHeight);
  4023. Object.defineProperty(_Element, 'clientWidth', _clientWidth);
  4024. let _onload = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onload'),
  4025. _set_onload = _onload.set;
  4026. _onload.set = function() {
  4027. if (this instanceof HTMLImageElement)
  4028. return true;
  4029. _set_onload.apply(this, arguments);
  4030. };
  4031. Object.defineProperty(HTMLElement.prototype, 'onload', _onload);
  4032. };
  4033.  
  4034. scripts['sport-express.ru'] = () => gardener('.js-relap__item',/>Реклама\s+<\//, {root:'.container', observe: true});
  4035.  
  4036. scripts['sports.ru'] = {
  4037. other: ['tribuna.com'],
  4038. now: () => {
  4039. // extra functionality: shows/hides panel at the top depending on scroll direction
  4040. createStyle([
  4041. '.user-panel__fixed { transition: top 0.2s ease-in-out!important; }',
  4042. '.popup__overlay.feedback { display: none!important }',
  4043. '.user-panel-up { top: -40px!important }',
  4044. '#branding-layout { margin-top: 100px!important }'
  4045. ], {id: 'fixes'}, false);
  4046. scriptLander(() => {
  4047. yandexRavenStub();
  4048. webpackJsonpFilter(/AdBlockDetector|addBranding|loadPlista/);
  4049. }, nullTools, yandexRavenStub);
  4050. },
  4051. dom: () => {
  4052. (function lookForPanel() {
  4053. let panel = _document.querySelector('.user-panel__fixed');
  4054. if (!panel)
  4055. setTimeout(lookForPanel, 100);
  4056. else
  4057. window.addEventListener(
  4058. 'wheel', function(e) {
  4059. if (e.deltaY > 0 && !panel.classList.contains('user-panel-up'))
  4060. panel.classList.add('user-panel-up');
  4061. else if (e.deltaY < 0 && panel.classList.contains('user-panel-up'))
  4062. panel.classList.remove('user-panel-up');
  4063. }, false
  4064. );
  4065. })();
  4066. }
  4067. };
  4068. scripts['stealthz.ru'] = {
  4069. dom: () => {
  4070. // skip timeout
  4071. let $ = _document.querySelector.bind(_document);
  4072. let [timer_1, timer_2] = [$('#timer_1'), $('#timer_2')];
  4073. if (!timer_1 || !timer_2)
  4074. return;
  4075. timer_1.style.display = 'none';
  4076. timer_2.style.display = 'block';
  4077. }
  4078. };
  4079.  
  4080. scripts['xatab-repack.net'] = {
  4081. other: ['rg-mechanics.org'],
  4082. now: () => scriptLander(() => {
  4083. Object.defineProperty(win, 'blocked', {
  4084. set: () => { throw 'and unlooked for.'; }
  4085. });
  4086. }, nullTools)
  4087. };
  4088.  
  4089. scripts['xittv.net'] = () => scriptLander(() => {
  4090. let logNames = ['setup', 'trigger', 'on', 'off', 'onReady', 'onError', 'getConfig', 'addPlugin', 'getAdBlock'];
  4091. let skipEvents = ['adComplete', 'adSkipped', 'adBlock', 'adRequest', 'adMeta', 'adImpression', 'adError', 'adTime', 'adStarted', 'adClick'];
  4092. let _jwplayer = void 0;
  4093. Object.defineProperty(win, 'jwplayer', {
  4094. get: () => _jwplayer,
  4095. set: x => {
  4096. _jwplayer = new Proxy(x, {
  4097. apply: (fun, that, args) => {
  4098. let res = fun.apply(that, args);
  4099. res = new Proxy(res, {
  4100. get: (obj, name) => {
  4101. if (logNames.includes(name) && obj[name] instanceof Function)
  4102. return new Proxy(obj[name], {
  4103. apply: (fun, that, args) => {
  4104. if (name === 'setup') {
  4105. let o = args[0];
  4106. if (o)
  4107. delete o.advertising;
  4108. }
  4109. if (name === 'on' || name === 'trigger') {
  4110. let events = typeof args[0] === 'string' ? args[0].split(" ") : null;
  4111. if (events.length === 1 && skipEvents.includes(events[0]))
  4112. return res;
  4113. if (events.length > 1) {
  4114. let names = [];
  4115. for (let event of events)
  4116. if (!skipEvents.includes(event))
  4117. names.push(event);
  4118. if (names.length > 0)
  4119. args[0] = names.join(" ");
  4120. else
  4121. return res;
  4122. }
  4123. }
  4124. let subres = fun.apply(that, args);
  4125. _console.warn(`jwplayer().${name}(`, ...args, `) >>`, res);
  4126. return subres;
  4127. }
  4128. });
  4129. return obj[name];
  4130. }
  4131. });
  4132. return res;
  4133. }
  4134. });
  4135. _console.log('jwplayer =', x);
  4136. }
  4137. });
  4138. });
  4139.  
  4140. scripts['yap.ru'] = {
  4141. other: ['yaplakal.com'],
  4142. now: () => {
  4143. gardener('form > table[id^="p_row_"]:nth-of-type(2)', /member1438|Administration/);
  4144. gardener('.icon-comments', /member1438|Administration|\/go\/\?http/, {parent:'tr', siblings:-2});
  4145. }
  4146. };
  4147.  
  4148. scripts['rambler.ru'] = {
  4149. other: ['championat.com', 'eda.ru', 'gazeta.ru', 'lenta.ru', 'media.eagleplatform.com', 'quto.ru', 'rns.online'],
  4150. now: () => {
  4151. selectiveCookies('detect_count');
  4152. scriptLander(() => {
  4153. // Prevent autoplay
  4154. if (!('EaglePlayer' in win)) {
  4155. let _EaglePlayer = void 0;
  4156. Object.defineProperty(win, 'EaglePlayer', {
  4157. enumerable: true,
  4158. get: () => _EaglePlayer,
  4159. set: x => {
  4160. if (x === _EaglePlayer)
  4161. return true;
  4162. _EaglePlayer = new Proxy(x, {
  4163. construct: (targ, args) => {
  4164. let player = new targ(...args);
  4165. if (!player.options) {
  4166. _console.log('EaglePlayer: no options', EaglePlayer);
  4167. return player;
  4168. }
  4169. Object.defineProperty(player.options, 'autoplay', {
  4170. get: () => false,
  4171. set: () => true
  4172. });
  4173. Object.defineProperty(player.options, 'scroll', {
  4174. get: () => false,
  4175. set: () => true
  4176. });
  4177. return player;
  4178. }
  4179. });
  4180. }
  4181. });
  4182. let _setAttribute = Function.prototype.apply.bind(_Element.setAttribute);
  4183. let isAutoplay = /^autoplay$/i;
  4184. _Element.setAttribute = function setAttribute(name) {
  4185. if (!this._stopped && isAutoplay.test(name)) {
  4186. _console.log('Prevented assigning autoplay attribute.');
  4187. return null;
  4188. }
  4189. return _setAttribute(this, arguments);
  4190. };
  4191. } else {
  4192. _console.log('EaglePlayer function already exists.');
  4193. if (inIFrame) {
  4194. let _setAttribute = Function.prototype.apply.bind(_Element.setAttribute);
  4195. let isAutoplay = /^autoplay$/i;
  4196. _Element.setAttribute = function setAttribute(name) {
  4197. if (!this._stopped && isAutoplay.test(name)) {
  4198. _console.log('Prevented assigning autoplay attribute.');
  4199. this._stopped = true;
  4200. this.play = () => {
  4201. _console.log('Prevented attempt to force-start playback.');
  4202. delete this.play;
  4203. };
  4204. return null;
  4205. }
  4206. return _setAttribute(this, arguments);
  4207. };
  4208. }
  4209. }
  4210. if (location.hostname.endsWith('.media.eagleplatform.com'))
  4211. return;
  4212. // Wrapper for adv loader settings in QW50aS1BZEJsb2Nr['7t7hystz']
  4213. let _contexts = new WeakMap();
  4214. Object.defineProperty(Object.prototype, 'Settings', {
  4215. set: function(val) {
  4216. if (typeof val === 'object' && 'Password' in val && 'Urls' in val) {
  4217. val.Urls = [];
  4218. _console.log('Adv.Client =', this, '\nAdv.Client.Settings =', val);
  4219. }
  4220. _contexts.set(this, val);
  4221. },
  4222. get: function() { return _contexts.get(this); }
  4223. });
  4224. // disable some logging
  4225. yandexRavenStub();
  4226. // prevent ads from loading
  4227. let blockPatterns = /\[[a-z]{1,4}\("0x[\da-f]+"\)\]|\.(rnet\.plus|24smi\.net|infox\.sg|lentainform\.com)\//i;
  4228. let _toString = Function.prototype.call.bind(Function.prototype.toString);
  4229. let _setTimeout = Function.prototype.apply.bind(win.setTimeout);
  4230. win.setTimeout = function(f) {
  4231. let str = (typeof f === 'function' ? _toString(f) : ''),
  4232. detected = blockPatterns.test(str);
  4233. if (!detected && f) {
  4234. try {
  4235. str = f.toString();
  4236. } catch(ignore) {};
  4237. if (str)
  4238. detected = blockPatterns.test(str);
  4239. }
  4240. if (detected) {
  4241. _console.warn('Stopped setTimeout for:', str.slice(0,100), '\u2026');
  4242. return null;
  4243. };
  4244. return _setTimeout(this, arguments);
  4245. };
  4246. /* Block partner "news" by stalling fetching them indefinitely */
  4247. let partners = /24smi\.net|infox\.sg|lentainform\.com|mirtesen\.ru/i;
  4248. win.fetch = new Proxy(win.fetch, {
  4249. apply: (fetch, ctx, args) => {
  4250. if (typeof args[0] === 'string' && partners.test(args[0])) {
  4251. _console.warn('Skipped fetch for', args[0]);
  4252. return new Promise(r => void r);
  4253. }
  4254. return Reflect.apply(fetch, ctx, args);
  4255. }
  4256. });
  4257. }, `let inIFrame = ${inIFrame}`, nullTools, yandexRavenStub)
  4258. },
  4259. dom: () => {
  4260. // remove utm_ form links
  4261. let parser = _document.createElement('a');
  4262. _document.addEventListener('mousedown', (e) => {
  4263. let t = e.target;
  4264. if (!t.href)
  4265. t = t.closest('A');
  4266. if (t && t.href) {
  4267. parser.href = t.href;
  4268. let remove = [];
  4269. let params = parser.search.slice(1).split('&').filter(name => {
  4270. if (name.startsWith('utm_')) {
  4271. remove.push(name);
  4272. return false;
  4273. }
  4274. return true;
  4275. });
  4276. if (remove.length)
  4277. _console.log('Removed parameters from link:', ...remove);
  4278. if (params.length)
  4279. parser.search = `?${params.join('&')}`;
  4280. else
  4281. parser.search = '';
  4282. t.href = parser.href;
  4283. }
  4284. }, false);
  4285. }
  4286. };
  4287.  
  4288. scripts['reactor.cc'] = {
  4289. other: ['joyreactor.cc', 'pornreactor.cc'],
  4290. now: () => {
  4291. selectiveEval();
  4292. scriptLander(() => {
  4293. let nt = new nullTools();
  4294. win.open = function(){
  4295. throw new Error('Redirect prevention.');
  4296. };
  4297. nt.define(win, 'Worker', function(){});
  4298. nt.define(win, 'JRCH', win.CoinHive);
  4299. }, nullTools);
  4300. },
  4301. click: function(e) {
  4302. let node = e.target;
  4303. if (node.nodeType === _Node.ELEMENT_NODE &&
  4304. node.style.position === 'absolute' &&
  4305. node.style.zIndex > 0)
  4306. node.parentNode.removeChild(node);
  4307. },
  4308. dom: function() {
  4309. let tid = void 0;
  4310. function probe() {
  4311. let node = selectNodeByTextContent('блокировщик рекламы');
  4312. if (!node) return;
  4313. while (node.parentNode.offsetHeight < 750 && node !== _document.body)
  4314. node = node.parentNode;
  4315. _setAttribute(node, 'style', 'background:none!important');
  4316. // stop observer
  4317. if (!tid) tid = setTimeout(() => this.disconnect(), 1000);
  4318. }
  4319. (new MutationObserver(probe))
  4320. .observe(_document, { childList:true, subtree:true });
  4321. }
  4322. };
  4323.  
  4324. scripts['auto.ru'] = () => {
  4325. let words = /Реклама|Яндекс.Директ|yandex_ad_/;
  4326. let userAdsListAds = (
  4327. '.listing-list > .listing-item,'+
  4328. '.listing-item_type_fixed.listing-item'
  4329. );
  4330. let catalogAds = (
  4331. 'div[class*="layout_catalog-inline"],'+
  4332. 'div[class$="layout_horizontal"]'
  4333. );
  4334. let otherAds = (
  4335. '.advt_auto,'+
  4336. '.sidebar-block,'+
  4337. '.pager-listing + div[class],'+
  4338. '.card > div[class][style],'+
  4339. '.sidebar > div[class],'+
  4340. '.main-page__section + div[class],'+
  4341. '.listing > tbody'
  4342. );
  4343. gardener(userAdsListAds, words, {root:'.listing-wrap', observe:true});
  4344. gardener(catalogAds, words, {root:'.catalog__page,.content__wrapper', observe:true});
  4345. gardener(otherAds, words);
  4346. };
  4347.  
  4348. scripts['rsload.net'] = {
  4349. load: () => {
  4350. let dis = _document.querySelector('label[class*="cb-disable"]');
  4351. if (dis)
  4352. dis.click();
  4353. },
  4354. click: e => {
  4355. let t = e.target;
  4356. if (t && t.href && (/:\/\/\d+\.\d+\.\d+\.\d+\//.test(t.href)))
  4357. t.href = t.href.replace('://','://rsload.net:rsload.net@');
  4358. }
  4359. };
  4360.  
  4361. let domain;
  4362. // add alternative domain names if present and wrap functions into objects
  4363. for (let name in scripts) {
  4364. if (scripts[name] instanceof Function)
  4365. scripts[name] = { now: scripts[name] };
  4366. for (domain of (scripts[name].other||[])) {
  4367. if (domain in scripts)
  4368. _console.log('Error in scripts list. Script for', name, 'replaced script for', domain);
  4369. scripts[domain] = scripts[name];
  4370. }
  4371. delete scripts[name].other;
  4372. }
  4373. // look for current domain in the list and run appropriate code
  4374. domain = _document.domain;
  4375. while (domain.includes('.')) {
  4376. if (domain in scripts) for (let when in scripts[domain])
  4377. switch(when) {
  4378. case 'now':
  4379. scripts[domain][when]();
  4380. break;
  4381. case 'dom':
  4382. _document.addEventListener('DOMContentLoaded', scripts[domain][when], false);
  4383. break;
  4384. default:
  4385. _document.addEventListener (when, scripts[domain][when], false);
  4386. }
  4387. domain = domain.slice(domain.indexOf('.') + 1);
  4388. }
  4389.  
  4390. // Batch script lander
  4391. if (!skipLander)
  4392. landScript(batchLand, batchPrepend);
  4393.  
  4394. { // JS Fixes Tools Menu
  4395. // Debug function, lists all unusual window properties
  4396. let _toString = Function.prototype.call.bind(Function.prototype.toString);
  4397. let isNativeFunction = new RegExp (`^[^{]*\\{[\\s\\r\\n]*\\[native\\scode\\][\\s\\r\\n]*\\}$`);
  4398. function getStrangeObjectsList() {
  4399. _console.warn('Window strangers list start');
  4400. let _skip = 'frames/self/window/webkitStorageInfo'.split('/');
  4401. for (let n of Object.getOwnPropertyNames(win)) {
  4402. let val = win[n];
  4403. if (val && !_skip.includes(n) && (win !== window && val !== window[n] || win === window) &&
  4404. (!(val instanceof Function) || val instanceof Function && !isNativeFunction.test(_toString(val))))
  4405. _console.log(`${n} =`, val);
  4406. }
  4407. _console.warn('Strangers list end');
  4408. }
  4409. // Debug function, lists all unusual Object.prototype properties
  4410. function getStrangeObjectsPrototypePropertiesList() {
  4411. _console.warn('Object.prototype strangers list start');
  4412. for (let n of Object.getOwnPropertyNames(win.Object.prototype)) {
  4413. let val = win.Object.prototype[n];
  4414. if (val &&
  4415. (!(val instanceof Function) || val instanceof Function && !isNativeFunction.test(_toString(val))))
  4416. _console.log(`${n} =`, val);
  4417. }
  4418. _console.warn('Strangers list end');
  4419. }
  4420.  
  4421. let openOptions = function() {
  4422. let ovl = _createElement('div'),
  4423. inner = _createElement('div');
  4424. ovl.style = (
  4425. 'position: fixed;'+
  4426. 'top:0; left:0;'+
  4427. 'bottom: 0; right: 0;'+
  4428. 'background: rgba(0,0,0,0.85);'+
  4429. 'z-index: 2147483647;'+
  4430. 'padding: 5em'
  4431. );
  4432. inner.style = (
  4433. 'background: whitesmoke;'+
  4434. 'font-size: 10pt;'+
  4435. 'color: black;'+
  4436. 'padding: 1em'
  4437. );
  4438. inner.textContent = 'JS Fixes Tools';
  4439. inner.appendChild(_createElement('br'));
  4440. inner.appendChild(_createElement('br'));
  4441. ovl.addEventListener(
  4442. 'click', function(e) {
  4443. if (e.target === ovl) {
  4444. ovl.parentNode.removeChild(ovl);
  4445. e.preventDefault();
  4446. }
  4447. e.stopPropagation();
  4448. }, false
  4449. );
  4450.  
  4451. let sObjBtn = _createElement('button');
  4452. sObjBtn.onclick = getStrangeObjectsList;
  4453. sObjBtn.textContent = 'Print (in console) list of unusual window properties';
  4454. let sOPPBtn = _createElement('button');
  4455. sOPPBtn.onclick = getStrangeObjectsPrototypePropertiesList;
  4456. sOPPBtn.textContent = 'Print (in console) list of unusual Object.prototype properties';
  4457. inner.appendChild(_createElement('br'));
  4458. inner.appendChild(sObjBtn);
  4459. inner.appendChild(_createElement('br'));
  4460. inner.appendChild(sOPPBtn);
  4461.  
  4462. _document.body.appendChild(ovl);
  4463. ovl.appendChild(inner);
  4464. };
  4465.  
  4466. // monitor keys pressed for Ctrl+Alt+Shift+J > s > f code
  4467. let opPos = 0, opKey = ['KeyJ','KeyS','KeyF'];
  4468. _document.addEventListener(
  4469. 'keydown', function(e) {
  4470. if ((e.code === opKey[opPos] || e.location) &&
  4471. (!!opPos || e.altKey && e.ctrlKey && e.shiftKey)) {
  4472. opPos += e.location ? 0 : 1;
  4473. e.stopPropagation();
  4474. e.preventDefault();
  4475. } else
  4476. opPos = 0;
  4477. if (opPos === opKey.length) {
  4478. opPos = 0;
  4479. openOptions();
  4480. }
  4481. }, false
  4482. );
  4483. }
  4484. })();