RU AdList JS Fixes

try to take over the world!

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

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