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