RU AdList JS Fixes

try to take over the world!

当前为 2020-05-08 提交的版本,查看 最新版本

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址