RU AdList JS Fixes

try to take over the world!

目前为 2020-02-15 提交的版本。查看 最新版本

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