RU AdList JS Fixes

try to take over the world!

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

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

QingJ © 2025

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