RU AdList JS Fixes

try to take over the world!

目前為 2020-02-14 提交的版本,檢視 最新版本

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