RU AdList JS Fixes

try to take over the world!

当前为 2022-09-30 提交的版本,查看 最新版本

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