RU AdList JS Fixes

try to take over the world!

当前为 2019-10-02 提交的版本,查看 最新版本

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