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