RU AdList JS Fixes

try to take over the world!

当前为 2020-05-21 提交的版本,查看 最新版本

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