RU AdList JS Fixes

try to take over the world!

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

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