RU AdList JS Fixes

try to take over the world!

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

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