RU AdList JS Fixes

try to take over the world!

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

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