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