RU AdList JS Fixes

try to take over the world!

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

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