RU AdList JS Fixes

try to take over the world!

目前為 2020-05-02 提交的版本,檢視 最新版本

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