RU AdList JS Fixes

try to take over the world!

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

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