Greasy Fork 还支持 简体中文。

RU AdList JS Fixes

try to take over the world!

目前為 2020-01-09 提交的版本,檢視 最新版本

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