RU AdList JS Fixes

try to take over the world!

当前为 2020-03-10 提交的版本,查看 最新版本

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