RU AdList JS Fixes

try to take over the world!

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

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