RU AdList JS Fixes

try to take over the world!

目前为 2020-03-19 提交的版本,查看 最新版本

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