RU AdList JS Fixes

try to take over the world!

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

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址