RU AdList JS Fixes

try to take over the world!

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

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