Greasy Fork 还支持 简体中文。

RU AdList JS Fixes

try to take over the world!

目前為 2023-11-27 提交的版本,檢視 最新版本

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