RU AdList JS Fixes

try to take over the world!

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

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