Greasy Fork is available in English.

RU AdList JS Fixes

try to take over the world!

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