RU AdList JS Fixes

try to take over the world!

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

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