RU AdList JS Fixes

try to take over the world!

目前為 2020-09-24 提交的版本,檢視 最新版本

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