RU AdList JS Fixes

try to take over the world!

当前为 2020-04-29 提交的版本,查看 最新版本

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

QingJ © 2025

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