RU AdList JS Fixes

try to take over the world!

当前为 2020-01-10 提交的版本,查看 最新版本

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