RU AdList JS Fixes

try to take over the world!

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

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