RU AdList JS Fixes

try to take over the world!

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

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