RU AdList JS Fixes

try to take over the world!

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

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