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.2
  5. // @description try to take over the world!
  6. // @author lainverse & dimisa
  7. // @supportURL https://greasyfork.org/en/scripts/19993-ru-adlist-js-fixes/feedback
  8. // @match *://*/*
  9. // @exclude *://auth.wi-fi.ru/*
  10. // @exclude *://*.alfabank.ru/*
  11. // @exclude *://alfabank.ru/*
  12. // @exclude *://*.unicreditbanking.net/*
  13. // @exclude *://*.telegram.org/*
  14. // @exclude *://telegram.org/*
  15. // @exclude *://trust.yandex.ru/*
  16. // @exclude *://diehard.yandex.ru/*
  17. // @exclude *://money.yandex.ru/*
  18. // @exclude *://beru.ru/*
  19. // @exclude *://*.ingress.com/*
  20. // @exclude *://hd.kinopoisk.ru/*
  21. // @grant GM_getValue
  22. // @grant GM_setValue
  23. // @grant GM_listValues
  24. // @grant GM_registerMenuCommand
  25. // @grant GM.cookie
  26. // @grant unsafeWindow
  27. // @grant window.close
  28. // @run-at document-start
  29. // ==/UserScript==
  30.  
  31. // jshint esversion: 8
  32. // jshint unused: true
  33. (function () {
  34. 'use strict';
  35.  
  36. const win = (unsafeWindow || window);
  37.  
  38. // MooTools are crazy enough to replace standard browser object window.Document: https://mootools.net/core
  39. // Occasionally their code runs before my script on some domains and causes all kinds of havoc.
  40. const
  41. _Document = Object.getPrototypeOf(HTMLDocument.prototype),
  42. _Element = Object.getPrototypeOf(HTMLElement.prototype);
  43. // dTree 2.05 in some cases replaces Node object
  44. const
  45. _Node = Object.getPrototypeOf(_Element);
  46.  
  47. // http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
  48. const
  49. // isOpera = (!!window.opr && !!window.opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0,
  50. // isChrome = !!window.chrome && !!window.chrome.webstore,
  51. isSafari =
  52. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0 ||
  53. (function (p) {
  54. return p.toString() === "[object SafariRemoteNotification]";
  55. })(!window.safari || window.safari.pushNotification),
  56. isFirefox = 'InstallTrigger' in win,
  57. inIFrame = (win.self !== win.top);
  58. const
  59. _bindCall = fun => Function.prototype.call.bind(fun),
  60. _getAttribute = _bindCall(_Element.getAttribute),
  61. _setAttribute = _bindCall(_Element.setAttribute),
  62. _removeAttribute = _bindCall(_Element.removeAttribute),
  63. _hasOwnProperty = _bindCall(Object.prototype.hasOwnProperty),
  64. _toString = _bindCall(Function.prototype.toString),
  65. _document = win.document,
  66. _de = _document.documentElement,
  67. _appendChild = _Document.appendChild.bind(_de),
  68. _removeChild = _Document.removeChild.bind(_de),
  69. _createElement = _Document.createElement.bind(_document),
  70. _querySelector = _Document.querySelector.bind(_document),
  71. _querySelectorAll = _Document.querySelectorAll.bind(_document),
  72. _attachShadow = ('attachShadow' in _Element) ? _bindCall(_Element.attachShadow) : null,
  73. _apply = Reflect.apply,
  74. _construct = Reflect.construct;
  75.  
  76. let skipLander = true;
  77. try {
  78. skipLander = !(isFirefox && 'StopIteration' in win);
  79. } catch (ignore) {}
  80.  
  81. const _console = {};
  82. _console.initConsole = () => {
  83. const keys = new Set();
  84. const _stopImmediatePropagation = _bindCall(Event.prototype.stopImmediatePropagation);
  85. win.addEventListener('message', e => {
  86. if (e.source === win || typeof e.data !== 'string')
  87. return;
  88. if (e.data.startsWith('_console.key')) {
  89. _stopImmediatePropagation(e);
  90. keys.add(e.data.slice(13));
  91. }
  92. if (keys.has(e.data.slice(0, 10))) {
  93. _stopImmediatePropagation(e);
  94. _console.log(`From: ${e.origin}\n${e.data.slice(11)}`);
  95. }
  96. });
  97. if (inIFrame) {
  98. const _postMessage = win.parent.postMessage.bind(win.parent);
  99. const key = Math.random().toString(36).substr(2).padStart(10, '0').slice(0, 10);
  100. _postMessage(`_console.key ${key}`, '*');
  101. const _Object_toString = _bindCall(Object.prototype.toString);
  102. const selfHandled = ['string', 'number', 'boolean', 'undefined'];
  103. const stringify = x => {
  104. if (selfHandled.includes(typeof x))
  105. return x;
  106. if (x === null)
  107. return 'null';
  108. if (typeof x === 'object') {
  109. if (x instanceof Window || x instanceof Document)
  110. return _Object_toString(x);
  111. if (x instanceof Element)
  112. return `<${x.tagName} ${Array.from(x.attributes).map(x => x.value ? `${x.name}="${x.value}"`: x.name).join(' ')}>`;
  113. let props = Object.getOwnPropertyNames(x);
  114. if (props.length > 30) {
  115. _console.log('ouch');
  116. props.splice(30, props.length - 30);
  117. props.push('\u2026');
  118. }
  119. return `[object {${props.join(', ')}}]`;
  120. }
  121. if (typeof x === 'function') {
  122. let str = _toString(x);
  123. return str.length > 200 ? `${str.slice(0, 200)}\u2026` : str;
  124. }
  125. return `[unhandled ${typeof x}]`;
  126. };
  127. const passIt = (...args) => {
  128. let strs = args.map(stringify);
  129. _postMessage(`${key} ${strs.join(' ')}`, '*', );
  130. };
  131. for (let name in win.console)
  132. _console[name] = passIt;
  133. } else {
  134. for (let name in win.console)
  135. _console[name] = console[name];
  136. _console._trace = _console.trace;
  137. _console.trace = (...args) => {
  138. if (!skipLander)
  139. return _console.warn(...args);
  140. _console.groupCollapsed(...args);
  141. _console._trace('Stack trace.');
  142. _console.groupEnd();
  143. };
  144. }
  145.  
  146. Object.freeze(_console);
  147. Object.defineProperty(win.console, 'clear', {
  148. value() {
  149. return null;
  150. }
  151. });
  152. };
  153. _console.initConsole();
  154.  
  155. const jsf = (function () {
  156. const opts = {};
  157. let getValue = (a, b) => b,
  158. setValue = () => null,
  159. listValues = () => [];
  160. try {
  161. [getValue, setValue, listValues] = [GM_getValue, GM_setValue, GM_listValues];
  162. } catch (ignore) {}
  163. // defaults
  164. opts.Lang = 'rus';
  165. opts.AbortExecutionStatistics = false;
  166. opts.AccessStatistics = false;
  167. opts.LogAttachedCSS = false;
  168. opts.BlockNotificationPermissionRequests = false;
  169. opts.ShowScriptHandlerCompatibilityWarning = true;
  170. // load actual values
  171. for (let name of listValues())
  172. opts[name] = getValue(name, opts[name]);
  173. const checkName = name => {
  174. if (!_hasOwnProperty(opts, name))
  175. throw new Error('Attempt to access missing option value.');
  176. return true;
  177. };
  178. return new Proxy(opts, {
  179. get(opts, name) {
  180. if (name === 'toString')
  181. return () => JSON.stringify(opts);
  182. if (checkName(name))
  183. return opts[name];
  184. },
  185. set(opts, name, value) {
  186. if (checkName(name)) {
  187. opts[name] = value;
  188. setValue(name, value);
  189. }
  190. return true;
  191. }
  192. });
  193. })();
  194.  
  195. if (jsf.BlockNotificationPermissionRequests && win.Notification && win.Notification.permission === 'default') {
  196. win.Notification.requestPermission = () => new Promise(resolve => resolve('denied'));
  197. Object.defineProperty(win.Notification, 'permission', {
  198. set() {},
  199. get() {
  200. return 'denied';
  201. }
  202. });
  203. }
  204.  
  205. if (isFirefox && // Exit on image pages in Fx
  206. _document.constructor.prototype.toString() === '[object ImageDocumentPrototype]')
  207. return;
  208.  
  209. // NodeList and HTMLCollection iterator polyfill
  210. // required for old versions of Safari and Chrome 49 (last available for WinXP)
  211. // https://jakearchibald.com/2014/iterators-gonna-iterate/
  212. if (!NodeList.prototype[Symbol.iterator])
  213. NodeList.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
  214. if (!HTMLCollection.prototype[Symbol.iterator])
  215. HTMLCollection.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
  216.  
  217. // Stub for missing "GM.cookie.list" in unsupported script managers
  218. if (GM.cookie === undefined)
  219. GM.cookie = {
  220. list: () => ({
  221. then: () => null
  222. })
  223. };
  224.  
  225. // Wrapper to run scripts designed to override objects available to other scripts
  226. // Required in old versions of Firefox (<58) or when running with Greasemonkey
  227. const
  228. batchLand = [],
  229. batchPrepend = new Set(),
  230. _APIString = `const win = window, isFirefox = ${isFirefox}, inIFrame = ${inIFrame}, _document = win.document, _de = _document.documentElement,
  231. _Document = Object.getPrototypeOf(HTMLDocument.prototype), _Element = Object.getPrototypeOf(HTMLElement.prototype), _Node = Object.getPrototypeOf(_Element),
  232. _appendChild = _Document.appendChild.bind(_de), _removeChild = _Document.removeChild.bind(_de), skipLander = ${skipLander},
  233. _createElement = _Document.createElement.bind(_document), _querySelector = _Document.querySelector.bind(_document),
  234. _querySelectorAll = _Document.querySelectorAll.bind(_document), _bindCall = fun => Function.prototype.call.bind(fun),
  235. _getAttribute = _bindCall(_Element.getAttribute), _setAttribute = _bindCall(_Element.setAttribute),
  236. _removeAttribute = _bindCall(_Element.removeAttribute), _hasOwnProperty = _bindCall(Object.prototype.hasOwnProperty),
  237. _toString = _bindCall(Function.prototype.toString), _apply = Reflect.apply, _construct = Reflect.construct;
  238. const GM = { info: { version: '0.0', scriptHandler: null }, cookie: { list: () => ({ then: () => null }) } };
  239. const jsf = ${jsf.toString()}, _console = {}; (${_console.initConsole.toString()})();`,
  240. landScript = (f, pre) => {
  241. const script = _createElement('script');
  242. script.textContent = `(()=>{${_APIString}${[...pre].join(';')};(${f.join(')();(')})();})();`;
  243. _appendChild(script);
  244. _removeChild(script);
  245. };
  246. let scriptLander = f => f();
  247. if (!skipLander) {
  248. scriptLander = (func, ...prepend) => {
  249. prepend.forEach(x => batchPrepend.add(x));
  250. batchLand.push(func);
  251. };
  252. _document.addEventListener(
  253. 'DOMContentLoaded', () => void(scriptLander = (f, ...prep) => landScript([f], prep)), false
  254. );
  255. }
  256.  
  257. function nullTools(opts) {
  258. /* jshint validthis: true */
  259. const nt = this;
  260. opts = opts || {};
  261.  
  262. function Stats() {
  263. const updated = new Map();
  264. const logged = new Map();
  265.  
  266. function printUpdated() {
  267. const prepared = [...updated].map(x => {
  268. const [prop, dir] = x;
  269. logged.set(prop, logged.get(prop) | dir);
  270. return `${prop} (${dir ^ (Stats.GET | Stats.SET) ? (dir & Stats.GET ? 'R' : 'W') : 'R/W'})`;
  271. }).sort();
  272. updated.clear();
  273. _console.log(`Accessed properties:\n * ${prepared.join('\n * ')}`);
  274. }
  275.  
  276. let logLock;
  277. this.log = async (prop, dir, doLog) => {
  278. if (!doLog) return;
  279. if (!(logged.get(prop) & dir))
  280. updated.set(prop, updated.get(prop) | dir);
  281. logLock = (logLock > 0 || !updated.size) ? logLock : setInterval(() => {
  282. printUpdated();
  283. logLock = clearInterval(logLock);
  284. }, 2500);
  285. };
  286. }
  287. Stats.GET = 1;
  288. Stats.SET = 2;
  289. Object.freeze(Stats);
  290. const stats = new Stats();
  291.  
  292. const log = async (...args) => opts.log && _console.log(...args);
  293. const isObjecty = x => (x !== null) && typeof x === 'object' || typeof x === 'function';
  294. const parsePath = path => {
  295. let root = win,
  296. chain = path.split('.'),
  297. link = chain.shift();
  298. for (; chain.length > 0; link = chain.shift()) {
  299. if (!isObjecty(root[link]))
  300. break;
  301. root = root[link];
  302. }
  303. return [root, link, chain];
  304. };
  305.  
  306. const namedObjects = new WeakMap();
  307.  
  308. nt.destroy = function (o, destroy) {
  309. if (!opts.destroy && !destroy && o instanceof Object)
  310. return;
  311. log('cleaning', o);
  312. try {
  313. for (let item in o) {
  314. if (item instanceof Object)
  315. nt.destroy(item);
  316. delete o[item];
  317. }
  318. } catch (e) {
  319. log('Error in object destructor', e);
  320. }
  321. };
  322.  
  323. nt.define = function (path, val, other = {}) {
  324. other.enumerable = other.enumerable || false;
  325. const [obj, prop, remainder] = parsePath(path);
  326. if (remainder.length) {
  327. _console.warn(`Unable to resolve ${remainder.join('.')} in ${path}`);
  328. return;
  329. }
  330. namedObjects.set(obj, path);
  331. nt.defineOn(obj, prop, val, path, other);
  332. };
  333.  
  334. nt.defineOn = function (obj, prop, val, path, other = {}) {
  335. path = path || ((obj === win) ? prop : `?.${prop}`);
  336. if (path[path.length - 1] === '.')
  337. path = `${path}${prop}`;
  338. const desc = Object.getOwnPropertyDescriptor(obj, prop);
  339. if (desc !== undefined && !desc.configurable) {
  340. _console.warn(`Unable to redefine not configurable ${prop} in`, obj);
  341. return;
  342. }
  343. const doLog = other.trace || jsf.AccessStatistics || opts.trace;
  344. Object.defineProperty(
  345. obj, prop, {
  346. get() {
  347. stats.log(path, Stats.GET, doLog);
  348. return val;
  349. },
  350. set(v) {
  351. stats.log(path, Stats.SET, doLog);
  352. if (v !== val) {
  353. log(`set ${prop} of`, obj, 'to', v);
  354. nt.destroy(v);
  355. }
  356. },
  357. enumerable: other.enumerable
  358. }
  359. );
  360. };
  361.  
  362. nt.proxy = function (obj, name, opts = {}) {
  363. if (name) namedObjects.set(obj, name);
  364. return new Proxy(
  365. obj, {
  366. get(that, prop) {
  367. if (prop in that)
  368. return that[prop];
  369. if (typeof prop === 'symbol') {
  370. if (prop === Symbol.toPrimitive)
  371. that[prop] = function (hint) {
  372. if (hint === 'string')
  373. return Object.prototype.toString.call(this);
  374. return `[missing toPrimitive] ${name} ${hint}`;
  375. };
  376. else if (prop === Symbol.toStringTag)
  377. that[prop] = () => 'Object';
  378. else {
  379. that[prop] = undefined;
  380. _console.trace('Missing', prop, 'in', name || '?', '>>', that[prop]);
  381. }
  382. return that[prop];
  383. }
  384. if (name) {
  385. that[prop] = nt.func(opts.val, `${name}.${prop}`, opts.log);
  386. return that[prop];
  387. }
  388. _console.trace('Missing', prop, 'in', namedObjects.get(that) || that);
  389. },
  390. set(that, prop, val) {
  391. if (val !== that[prop]) {
  392. log('skip set', prop, 'of', namedObjects.get(that) || that, 'to', val);
  393. nt.destroy(val);
  394. }
  395. return true;
  396. }
  397. }
  398. );
  399. };
  400.  
  401. nt.func = (val, name, log = opts.log || opts.trace) => nt.proxy((() => {
  402. let f = function () {
  403. if (log) _console.trace(`call ${name || ''}(`, ...arguments, `) return`, val);
  404. return val;
  405. };
  406. if (name) namedObjects.set(f, name);
  407. return f;
  408. })());
  409.  
  410. nt.NULL = {
  411. val: null
  412. };
  413. Object.freeze(nt.NULL);
  414.  
  415. Object.freeze(nt);
  416. }
  417. nullTools.toString = new Proxy(nullTools.toString, {
  418. apply(...args) {
  419. return `${_apply(...args)} let nt = new nullTools();`;
  420. }
  421. });
  422. let nt = new nullTools();
  423.  
  424. // Creates and return protected style (unless protection is manually disabled).
  425. // Protected style will re-add itself on removal and remaind enabled on attempt to disable it.
  426.  
  427. const createStyle = (function createStyleModule() {
  428. function createStyleElement(rules, opts) {
  429. const style = _createElement('style');
  430. Object.assign(style, opts.props);
  431. opts.root.appendChild(style);
  432.  
  433. if (style.sheet) // style.sheet is only available when style attached to DOM
  434. rules.forEach(style.sheet.insertRule.bind(style.sheet));
  435. else
  436. style.textContent = rules.join('\n');
  437.  
  438. if (opts.protect) {
  439. Object.defineProperty(style, 'sheet', {
  440. value: null,
  441. enumerable: true
  442. });
  443. Object.defineProperty(style, 'disabled', { //pretend to be disabled
  444. enumerable: true,
  445. set() {},
  446. get() {
  447. return true;
  448. }
  449. });
  450. (new MutationObserver(
  451. () => opts.root.removeChild(style)
  452. )).observe(style, {
  453. childList: true
  454. });
  455. }
  456.  
  457. return style;
  458. }
  459.  
  460. // functions to parse object-based rulesets
  461. function parseRule(rec) {
  462. /* jshint validthis: true */
  463. return this.concat(rec[0], ' {\n', Object.entries(rec[1]).map(parseProperty, this + '\t').join('\n'), '\n', this, '}');
  464. }
  465.  
  466. function parseProperty(rec) {
  467. /* jshint validthis: true */
  468. return rec[1] instanceof Object ? parseRule.call(this, rec) : `${this}${rec[0].replace(/_/g, '-')}: ${rec[1]};`;
  469. }
  470.  
  471. // main
  472. const createStyle = (rules, opts) => {
  473. // parse options
  474. opts = Object.assign({
  475. protect: true,
  476. root: _de,
  477. type: 'text/css'
  478. }, opts);
  479. // move style properties into separate property
  480. // { a, b, ...rest } construction is not available in Fx 52
  481. opts.props = Object.assign({}, opts);
  482. delete opts.props.protect;
  483. delete opts.props.root;
  484. // store binded methods instead of element
  485. opts.root = {
  486. appendChild: opts.root.appendChild.bind(opts.root),
  487. removeChild: opts.root.removeChild.bind(opts.root)
  488. };
  489.  
  490. // convert rules set into an array if it isn't one already
  491. rules = Array.isArray(rules) ? rules : rules instanceof Object ? Object.entries(rules).map(parseRule, '') : [rules];
  492.  
  493. // could be reassigned when protection triggered
  494. let style = createStyleElement(rules, opts);
  495.  
  496. if (!opts.protect)
  497. return style;
  498.  
  499. const replaceStyle = () => new Promise(
  500. resolve => setTimeout(re => re(createStyleElement(rules, opts)), 0, resolve)
  501. ).then(st => (style = st)); // replace poiner to style object with a new style object
  502.  
  503. (new MutationObserver(ms => {
  504. for (let m of ms)
  505. for (let node of m.removedNodes)
  506. if (node === style) replaceStyle();
  507. })).observe(_de, {
  508. childList: true
  509. });
  510.  
  511. if (jsf.LogAttachedCSS)
  512. _console.log(`Attached CSS:\n${rules.join('\n')}`);
  513.  
  514. return style;
  515. };
  516. createStyle.toString = () => `const createStyle = (${createStyleModule.toString()})();`;
  517. return createStyle;
  518. })();
  519.  
  520. // aborts currently running script with ReferenceError on specific property access
  521. // in case of inline script also checks if it contains specific pattern in it
  522.  
  523. const removeOwnFootprint = e => (e.stack = e.stack.split('\n').filter(x => !x.includes('-extension://')).join('\n'), e);
  524. const abortExecution = (function abortExecutionModule() {
  525. let map = new Map(),
  526. cnt = new Map(),
  527. stack = 0;
  528. const printCounters = (cnts) => {
  529. let s = '';
  530. for (let cntr of cnts)
  531. s += `\n * ${cntr[0]}: ${cntr[1]}`;
  532. return s;
  533. };
  534. const logger = id => {
  535. if (!jsf.AbortExecutionStatistics)
  536. return;
  537. let {
  538. path,
  539. mode
  540. } = map.get(id);
  541. let prop = `${path} ${mode.toString().replace('Symbol','')}`;
  542. cnt.set(prop, (cnt.get(prop) || 0) + 1);
  543. stack++;
  544. setTimeout(() => {
  545. stack--;
  546. if (!stack)
  547. console.log('Abort execution counters:', printCounters(Array.from(cnt.entries())));
  548. }, 1000);
  549. };
  550. const isObjecty = x => (x !== null) && typeof x === 'object' || typeof x === 'function';
  551. const Mode = {
  552. Get: Symbol('Read'),
  553. Set: Symbol('Write'),
  554. All: Symbol('Access'),
  555. InlineScript: Symbol('InlineScript')
  556. };
  557. Object.freeze(Mode);
  558.  
  559. const abortExecution = function abortExecution(mode, path, conf = {}) {
  560. let root = conf.root || win,
  561. chain = path.split('.'),
  562. postponed = false;
  563. const postpone = (link, chain) => {
  564. postponed = true;
  565. let _val;
  566. try {
  567. Object.defineProperty(root, link, {
  568. get() {
  569. return _val;
  570. },
  571. set(val) {
  572. _val = val;
  573. conf.root = val;
  574. conf.fullPath = conf.fullPath || path;
  575. abortExecution(mode, chain.join('.'), conf);
  576. }
  577. });
  578. } catch (e) {
  579. _console.warn(`Unable to set postpone point at ${link} in ${path}\n`, e);
  580. }
  581. };
  582. while (chain.length > 1) {
  583. let link = chain.shift();
  584. if (!isObjecty(root[link])) {
  585. if (conf.breakOnMissing)
  586. break;
  587. postpone(link, chain);
  588. break;
  589. }
  590. root = root[link];
  591. }
  592. path = conf.fullPath || path;
  593. if (postponed) {
  594. if (conf.breakOnMissing)
  595. _console.log(`Unable to locate "${path}", abort anchor skipped.`);
  596. return;
  597. }
  598. const target = chain[0];
  599. const message = `${target} is not defined`;
  600. const des = Object.getOwnPropertyDescriptor(root, target);
  601. if (des && des.get !== undefined)
  602. return;
  603. const id = Math.random().toString(36).substr(2);
  604. map.set(id, {
  605. path: path,
  606. mode: mode
  607. });
  608. win.addEventListener('error', e => {
  609. if (e.error && e.error.message === message)
  610. e.stopImmediatePropagation();
  611. }, false);
  612. const get = Symbol('get');
  613. const set = Symbol('set');
  614.  
  615. const check = (mode === Mode.InlineScript) ?
  616. () => {
  617. const script = _document.currentScript;
  618. if (script && script.src === '' &&
  619. (!conf.pattern || conf.pattern.test(script.textContent))) {
  620. logger(id);
  621. throw removeOwnFootprint(new ReferenceError(message));
  622. }
  623. } : io => {
  624. if (io === set && mode === Mode.Get ||
  625. io === get && mode === Mode.Set)
  626. return;
  627. logger(id);
  628. throw removeOwnFootprint(new ReferenceError(message));
  629. };
  630.  
  631. let _val = root[target];
  632. Object.defineProperty(root, target, {
  633. get() {
  634. check(get);
  635. return _val;
  636. },
  637. set(v) {
  638. check(set);
  639. _val = v;
  640. }
  641. });
  642. };
  643. abortExecution.onGet = (path, conf) => abortExecution(Mode.Get, path, conf);
  644. abortExecution.onSet = (path, conf) => abortExecution(Mode.Set, path, conf);
  645. abortExecution.onAll = (path, conf) => abortExecution(Mode.All, path, conf);
  646. abortExecution.inlineScript = (path, conf) => abortExecution(Mode.InlineScript, path, conf);
  647. abortExecution.toString = () => ` const abortExecution = (${abortExecutionModule.toString()})();`;
  648. return abortExecution;
  649. })();
  650.  
  651. // Fake objects of advertisement networks to break their workflow
  652. // Popular adblock detector
  653. function deployFABStub(root) {
  654. if (!('fuckAdBlock' in root)) {
  655. let FuckAdBlock = function (options) {
  656. let self = this;
  657. self._options = {
  658. checkOnLoad: false,
  659. resetOnEnd: false,
  660. checking: false
  661. };
  662. self.setOption = function (opt, val) {
  663. if (val)
  664. self._options[opt] = val;
  665. else
  666. Object.assign(self._options, opt);
  667. };
  668. if (options)
  669. self.setOption(options);
  670.  
  671. self._var = {
  672. event: {}
  673. };
  674. self.clearEvent = function () {
  675. self._var.event.detected = [];
  676. self._var.event.notDetected = [];
  677. };
  678. self.clearEvent();
  679.  
  680. self.on = function (detected, fun) {
  681. self._var.event[detected ? 'detected' : 'notDetected'].push(fun);
  682. return self;
  683. };
  684. self.onDetected = function (cb) {
  685. return self.on(true, cb);
  686. };
  687. self.onNotDetected = function (cb) {
  688. return self.on(false, cb);
  689. };
  690. self.emitEvent = function () {
  691. for (let fun of self._var.event.notDetected)
  692. fun();
  693. if (self._options.resetOnEnd)
  694. self.clearEvent();
  695. return self;
  696. };
  697. self._creatBait = () => null;
  698. self._destroyBait = () => null;
  699. self._checkBait = function () {
  700. setTimeout((() => self.emitEvent()), 1);
  701. };
  702. self.check = function () {
  703. self._checkBait();
  704. return true;
  705. };
  706.  
  707. let callback = function () {
  708. if (self._options.checkOnLoad)
  709. setTimeout(self.check, 1);
  710. };
  711. root.addEventListener('load', callback, false);
  712. };
  713. nt.defineOn(root, 'FuckAdBlock', FuckAdBlock);
  714. nt.defineOn(root, 'fuckAdBlock', new FuckAdBlock({
  715. checkOnLoad: true,
  716. resetOnEnd: true
  717. }));
  718. }
  719. }
  720. // new version of fAB adapting to fake API
  721. // scriptLander(() => deployFABStub(win), nullTools); // so it's disabled by default for now
  722.  
  723. scriptLander(() => {
  724. // VideoJS player wrapper
  725. {
  726. let _videojs = win.videojs;
  727. Object.defineProperty(win, 'videojs', {
  728. get() {
  729. return _videojs;
  730. },
  731. set(f) {
  732. if (f === _videojs)
  733. return true;
  734. _console.log('videojs =', f);
  735. _videojs = new Proxy(f, {
  736. apply(fun, that, args) {
  737. _console.log('videojs(', ...args, ')');
  738. const params = args[1];
  739. if (params) {
  740. if (params.hasAd)
  741. params.hasAd = false;
  742. if (params.plugins && params.plugins.vastClient)
  743. delete params.plugins.vastClient;
  744. // disable unmuted autoplay (muted used for preview purposes)
  745. if (params.autoplay && !params.muted)
  746. params.autoplay = false;
  747. }
  748. const res = _apply(fun, that, args);
  749. if (res.seed)
  750. res.seed = () => null;
  751. if (res.on && res.off) {
  752. const logPlayer = () => {
  753. _console.log('player =', res);
  754. res.off('playing', logPlayer);
  755. };
  756. res.on('playing', logPlayer);
  757. }
  758. return res;
  759. }
  760. });
  761. }
  762. });
  763. }
  764.  
  765. // Set a little trap for BodyClick ads
  766. abortExecution.onSet('__BC_domain');
  767.  
  768. // Yandex API (ADBTools, Metrika)
  769. let hostname = location.hostname;
  770. if ( // Thank you, Greasemonkey, now I have to check for this. -_-
  771. location.protocol === 'about:' ||
  772. // Google likes to define odd global variables like Ya
  773. hostname.startsWith('google.') || hostname.includes('.google.') ||
  774. // Also, Yandex uses their Ya object for a lot of things on their pages and
  775. // wrapping it may cause problems. It's better to skip it in some cases.
  776. ((hostname.startsWith('yandex.') || hostname.includes('.yandex.')) &&
  777. /^\/((yand)?search|images|health)/i.test(location.pathname) && !hostname.startsWith('news.')) ||
  778. // Also skip on these following sites since they use
  779. // code minification which generated global Ya variable.
  780. hostname.endsWith('chatango.com') || hostname.endsWith('github.io') ||
  781. hostname.endsWith('grimtools.com') || hostname.endsWith('poeplanner.com'))
  782. return;
  783.  
  784. let YaProps = new Set();
  785.  
  786. function setObfuscatedProperty(Ya, rootProp, obj, name) {
  787. if (YaProps.has(rootProp))
  788. return;
  789. _console.trace(`Ya.${rootProp} = Ya.${name}`);
  790. nt.defineOn(Ya, rootProp, Ya[name], 'Ya.');
  791. YaProps.add(rootProp);
  792. for (let prop in obj)
  793. delete obj[prop];
  794. for (let prop in Ya[name])
  795. obj[prop] = Ya[name][prop];
  796. }
  797.  
  798. function onObfuscatedProperty(Ya, rootProp, obj) {
  799. if ('AdvManager' in obj || 'AdvManagerStatic' in obj || 'isAllowedRepeatAds' in obj) {
  800. setObfuscatedProperty(Ya, rootProp, obj, 'Context');
  801. return Ya.Context;
  802. }
  803. if ('create' in obj && 'createAdaptive' in obj && 'createScroll' in obj) {
  804. setObfuscatedProperty(Ya, rootProp, obj, 'adfoxCode');
  805. return Ya.adfoxCode;
  806. }
  807. return new Proxy(obj, {
  808. set(target, prop, val) {
  809. if (prop === 'AdvManager' || prop === 'isAllowedRepeatAds') {
  810. setObfuscatedProperty(Ya, rootProp, obj, 'Context');
  811. return true;
  812. }
  813. if (prop === 'create' && 'createAdaptive' in obj && 'createScroll' in obj ||
  814. prop === 'createScroll' && 'create' in obj && 'createAdaptive' in obj ||
  815. prop === 'createAdaptive' && 'create' in obj && 'createScroll' in obj) {
  816. setObfuscatedProperty(Ya, rootProp, obj, 'adfoxCode');
  817. return true;
  818. }
  819. target[prop] = val;
  820. return true;
  821. },
  822. get(target, prop) {
  823. if (prop === 'AdvManager' && !(prop in target)) {
  824. _console.trace(`Injected missing ${prop} in Ya.${rootProp}.`);
  825. target[prop] = Ya.Context[prop];
  826. }
  827. return target[prop];
  828. }
  829. });
  830. }
  831. let Rum = {
  832. getSettings: nt.func([], 'Ya.Rum.getSettings'),
  833. getVarsList: nt.func([], 'Ya.Rum.getVarsList'),
  834. ajaxStart: 0,
  835. ajaxComplete: 0,
  836. enabled: true,
  837. vsChanged: false,
  838. vsStart: 'visible',
  839. ERROR_LEVEL: nt.proxy({
  840. ERROR: 0,
  841. WARN: 0,
  842. INFO: 0
  843. }, 'Ya.Rum.ERROR_LEVEL'),
  844. _tti: null,
  845. _markListeners: nt.proxy({}, 'Ya.Rum._markListeners'),
  846. _periodicTasks: nt.proxy({}, 'Ya.Rum._periodicTasks')
  847. };
  848. [
  849. '__timeMarks', '_timeMarks', '__deltaMarks', '_deltaMarks',
  850. '__defRes', '_defRes', '__defTimes', '_defTimes', '_vars',
  851. 'commonVars'
  852. ].forEach(name => void(Rum[name] = []));
  853. Rum = nt.proxy(Rum, 'Ya.Rum', nt.NULL);
  854. let Ya = new Proxy({}, {
  855. set(obj, prop, val) {
  856. if (val === obj[prop])
  857. return true;
  858. if (prop === 'Rum') {
  859. nt.defineOn(obj, prop, Rum, 'Ya.');
  860. YaProps.add(prop);
  861. Object.assign(val, Rum);
  862. }
  863. if (YaProps.has(prop)) {
  864. _console.log(`Ya.${prop} \u2260`, val);
  865. return true;
  866. }
  867. if (typeof val === 'object' && prop !== '__inline_params__' && !('length' in val))
  868. val = onObfuscatedProperty(Ya, prop, val);
  869. obj[prop] = val;
  870. _console.log(`Ya.${prop} =`, val);
  871. return true;
  872. },
  873. get(obj, prop) {
  874. return obj[prop];
  875. }
  876. });
  877. let callWithParams = function (f) {
  878. f.call(this, Ya.__inline_params__ || {});
  879. Ya.__inline_params__ = null;
  880. };
  881. nt.defineOn(Ya, 'callWithParams', callWithParams, 'Ya.');
  882. nt.defineOn(Ya, 'PerfCounters', nt.proxy({
  883. __cacheEvents: []
  884. }, 'Ya.PerfCounters', nt.NULL), 'Ya.');
  885. nt.defineOn(Ya, '__isSent', true, 'Ya.');
  886. nt.defineOn(Ya, 'confirmUrl', '', 'Ya.');
  887. nt.defineOn(Ya, 'Direct', nt.proxy({}, 'Ya.Direct', nt.NULL), 'Ya.');
  888. nt.defineOn(Ya, 'mediaCode', nt.proxy({
  889. create() {
  890. if (inIFrame) {
  891. _console.log('Removed body of ad-frame.');
  892. _document.documentElement.removeChild(_document.body);
  893. }
  894. }
  895. }, 'Ya.mediaCode', nt.NULL), 'Ya.');
  896. let extra = nt.proxy({
  897. extra: nt.proxy({
  898. match: 0,
  899. confirm: '',
  900. src: ''
  901. }),
  902. id: 0,
  903. percent: 100,
  904. threshold: 1
  905. });
  906. nt.defineOn(Ya, '_exp', nt.proxy({
  907. id: 0,
  908. coin: 0,
  909. choose: nt.func(extra, 'Ya._exp.choose'),
  910. get(prop) {
  911. return _hasOwnProperty(extra, prop) ? extra[prop] : null;
  912. },
  913. getId: nt.func(0, 'Ya._exp.getId'),
  914. defaultVersion: extra,
  915. getExtra: nt.func(extra.extra, 'Ya._exp.getExtra'),
  916. getDefaultExtra: nt.func(extra.extra, 'Ya._exp.getDefaultExtra'),
  917. versions: [extra]
  918. }), 'Ya.');
  919. nt.defineOn(Ya, 'c', nt.func(null, 'Ya.c'), 'Ya.');
  920. nt.defineOn(Ya, 'ADBTools', function () {
  921. this.getCurrentState = nt.func(true, 'Ya.ADBTools().getCurrentState');
  922. return nt.proxy(this, 'Ya.ADBTools', nt.NULL);
  923. }, 'Ya.');
  924. nt.defineOn(Ya, 'AdDetector', nt.proxy({}, 'Ya.AdDetector', nt.NULL), 'Ya.');
  925. let definePr = o => {
  926. Object.defineProperty(o, 'pr', {
  927. set() {},
  928. get() {
  929. return Math.floor(Math.random() * 1e6) + 1;
  930. }
  931. });
  932. };
  933. let adfoxCode = {
  934. forcedDirectLoadingExp: nt.proxy({
  935. isLoadingTurnedOn: false,
  936. isExp: false
  937. }),
  938. isLoadingTurnedOn: false,
  939. xhrExperiment: nt.proxy({
  940. isXhr: true,
  941. isControl: true
  942. }),
  943. matchidManager: nt.proxy({}, 'Ya.adfoxCode.matchidManager', nt.NULL),
  944. _: []
  945. };
  946. definePr(adfoxCode);
  947. [
  948. 'clearSession', 'create', 'createAdaptive', 'createScroll',
  949. 'destroy', 'moduleLoad', 'reload', 'setModule'
  950. ].forEach(name => void(adfoxCode[name] = nt.func(null, `Ya.adfoxCode.${name}`)));
  951. nt.defineOn(Ya, 'adfoxCode', nt.proxy(adfoxCode, 'Ya.adfoxCode', nt.NULL), 'Ya.');
  952. let managerForAdfox = {
  953. loaderVersion: 1,
  954. isCurrrencyExp: true,
  955. isReady: nt.func(true, 'Ya.headerBidding.managerForAdfox.isReady'),
  956. getRequestTimeout: nt.func(
  957. 300 + Math.floor(Math.random() * 100),
  958. 'Ya.headerBidding.managerForAdfox.getRequestTimeout'
  959. )
  960. };
  961. let headerBidding = nt.proxy({
  962. setSettings(opts) {
  963. if (!(opts && opts.adUnits))
  964. return null;
  965. let ids = [];
  966. for (let unit of opts.adUnits)
  967. ids.push(unit.code);
  968. createStyle(`#${ids.join(', #')} { display: none !important }`);
  969. },
  970. pushAdUnits: nt.func(null, 'Ya.headerBidding.pushAdUnits'),
  971. managerForAdfox: nt.proxy(managerForAdfox, 'Ya.headerBidding.managerForAdfox', nt.NULL)
  972. });
  973. definePr(headerBidding);
  974. nt.defineOn(Ya, 'headerBidding', headerBidding, 'Ya.');
  975.  
  976. let AdvManager = function () {
  977. this.render = function (o) {
  978. if (!o.renderTo)
  979. return;
  980. let placeholder = _document.getElementById(o.renderTo);
  981. if (!placeholder)
  982. return _console.warn('Ya.AdvManager.render call w/o placeholder', o);
  983. let parent = placeholder.parentNode;
  984. placeholder.style = 'display:none!important';
  985. parent.style = (parent.getAttribute('style') || '') + 'height:auto!important';
  986. // fix for Yandex TV pages
  987. if (location.hostname.startsWith('tv.yandex.')) {
  988. let sibling = placeholder.previousSibling;
  989. if (sibling && sibling.classList && sibling.classList.contains('tv-spin'))
  990. sibling.style.display = 'none';
  991. }
  992. };
  993. this.constructor = Object;
  994. return nt.proxy(this, 'Ya.AdvManager', nt.NULL);
  995. };
  996. nt.defineOn(Ya, 'Context', new Proxy({
  997. __longExperiment: null,
  998. _callbacks: nt.proxy([]),
  999. _asyncModeOn: true,
  1000. _init: nt.func(null, 'Ya.Context._init'),
  1001. _load_callbacks: nt.proxy([]),
  1002. performanceStorage: nt.proxy({}),
  1003. processCallbacks: nt.func(null, 'Ya.Context.processCallbacks'),
  1004. isAllowedRepeatAds: nt.func(null, 'Ya.Context.isAllowedRepeatAds'),
  1005. isNewLoader: nt.func(false, 'Ya.Context.isNewLoader'),
  1006. getItem: nt.func(null, 'Ya.Context.getItem'),
  1007. AdvManager: new AdvManager(),
  1008. AdvManagerStatic: new AdvManager()
  1009. }, {
  1010. get(obj, prop) {
  1011. if (prop in obj)
  1012. return obj[prop];
  1013. _console.trace(`Ya.Context.${prop} = Ya.Context.AdvManager`);
  1014. obj[prop] = obj.AdvManager;
  1015. return obj[prop];
  1016. },
  1017. set() {
  1018. return true;
  1019. }
  1020. }), 'Ya.');
  1021. let Metrika = function Metrika(x) {
  1022. this._ecommerce = '';
  1023. if (x && 'id' in x)
  1024. this.id = x.id;
  1025. else
  1026. this.id = 0;
  1027. return nt.proxy(this, 'Ya.Metrika', nt.NULL);
  1028. };
  1029. Metrika.counters = () => Ya._metrika.counters;
  1030. nt.defineOn(Ya, 'Metrika', Metrika, 'Ya.');
  1031. nt.defineOn(Ya, 'Metrika2', Metrika, 'Ya.');
  1032. let counter = new Metrika();
  1033. nt.defineOn(Ya, '_metrika', nt.proxy({
  1034. counter: counter,
  1035. counters: [counter],
  1036. hitParam: {},
  1037. counterNum: 0,
  1038. hitId: 0,
  1039. v: 1,
  1040. i: 0,
  1041. _globalMetrikaHitId: 0,
  1042. getCounters: null,
  1043. dataLayer: null,
  1044. f1: null
  1045. }), 'Ya.');
  1046. nt.defineOn(Ya, '_globalMetrikaHitId', 0, 'Ya.');
  1047. counter = {};
  1048. [
  1049. 'stringifyParams', '_getVars',
  1050. 'getUid', 'getUrl', 'getHash'
  1051. ].forEach(name => void(counter[name] = nt.func('', `Ya.counter.${name}`)));
  1052. nt.defineOn(Ya, 'counter', nt.proxy(counter, 'Ya.counter', nt.NULL), 'Ya.');
  1053. nt.defineOn(Ya, 'jserrors', [], 'Ya.');
  1054. nt.defineOn(Ya, 'onerror', nt.func(null, 'Ya.onerror'), 'Ya.');
  1055. let error_on_access = false;
  1056. if ('Ya' in win)
  1057. try {
  1058. _console.log('Found existing Ya object:', win.Ya);
  1059. for (let prop in win.Ya)
  1060. Ya[prop] = win.Ya[prop];
  1061. } catch (ignore) {
  1062. error_on_access = true;
  1063. }
  1064. if (!error_on_access && // some people don't know how to export only necessary stuff into global context
  1065. location.hostname !== 'material.io') { // so, here is an exception for one of such cases
  1066. for (let prop in Ya)
  1067. if (prop !== '__inline_params__')
  1068. YaProps.add(prop);
  1069. nt.define('Ya', Ya);
  1070. } else
  1071. _console.warn('Looks like window.Ya blocked with error-on-access scriptlet.');
  1072. // Yandex.Metrika callbacks
  1073. let yandex_metrika_callbacks = [];
  1074. _document.addEventListener(
  1075. 'DOMContentLoaded', () => {
  1076. yandex_metrika_callbacks.forEach((f) => f && f.call(window));
  1077. yandex_metrika_callbacks.length = 0;
  1078. yandex_metrika_callbacks.push = (f) => setTimeout(f, 0);
  1079. }, false
  1080. );
  1081. nt.define('yandex_metrika_callbacks', yandex_metrika_callbacks);
  1082. }, nullTools, createStyle, abortExecution);
  1083.  
  1084. // Yandex Raven stub (some monitoring sub-system)
  1085. function yandexRavenStub() {
  1086. let nt = new nullTools({
  1087. log: true
  1088. });
  1089. nt.define('Raven', nt.proxy({
  1090. context(f) {
  1091. return f();
  1092. },
  1093. config: nt.func(
  1094. nt.proxy({}, 'Raven.config', {
  1095. val: nt.proxy({}, 'Raven.config()..', nt.NULL)
  1096. }), 'Raven.config')
  1097. }, 'Raven', nt.NULL));
  1098. }
  1099.  
  1100. // Based on https://greasyfork.org/en/scripts/21937-moonwalk-hdgo-kodik-fix v0.8
  1101. {
  1102. const log = name => _console.log(`Player FIX: Detected ${name} player in ${location.href}`);
  1103. const removeVast = (data) => {
  1104. if (data && typeof data === 'object') {
  1105. _console.log('Player configuration:', data);
  1106. if (data.advert_script && data.advert_script !== '') {
  1107. _console.log('Set data.advert_script to empty string.');
  1108. data.advert_script = '';
  1109. }
  1110. let keys = Object.getOwnPropertyNames(data);
  1111. let isVast = name => /vast|clickunder/.test(name);
  1112. if (!keys.some(isVast))
  1113. return data;
  1114. for (let key of keys)
  1115. if (typeof data[key] === 'object' && key !== 'links') {
  1116. _console.log(`Removed data.${key}:`, data[key]);
  1117. delete data[key];
  1118. }
  1119. if (data.chain) {
  1120. let need = [],
  1121. drop = [],
  1122. links = data.chain.split('.');
  1123. for (let link of links)
  1124. if (!isVast(link))
  1125. need.push(link);
  1126. else
  1127. drop.push(link);
  1128. _console.log('Dropped from the chain:', ...drop);
  1129. data.chain = need.join('.');
  1130. }
  1131. }
  1132. return data;
  1133. };
  1134.  
  1135. _document.addEventListener(
  1136. 'DOMContentLoaded',
  1137. function () {
  1138. if ('video_balancer_options' in win && 'event_callback' in win) {
  1139. log('Moonwalk');
  1140. if (win.video_balancer_options.adv)
  1141. removeVast(win.video_balancer_options.adv);
  1142. if ('_mw_adb' in win)
  1143. Object.defineProperty(win, '_mw_adb', {
  1144. set() {},
  1145. get() {
  1146. return false;
  1147. }
  1148. });
  1149. } else if (win.startKodikPlayer !== undefined) {
  1150. log('Kodik');
  1151. // skip attempt to block access to HD resolutions
  1152. const chainCall = new Proxy({}, {
  1153. get() {
  1154. return () => chainCall;
  1155. }
  1156. });
  1157. if (win.$ && win.$.prototype && win.$.prototype.addClass) {
  1158. let $addClass = win.$.prototype.addClass;
  1159. win.$.prototype.addClass = function (className) {
  1160. if (className === 'blocked')
  1161. return chainCall;
  1162. return $addClass.apply(this, arguments);
  1163. };
  1164. }
  1165. // remove ad links from the metadata
  1166. let _ajax = win.$.ajax;
  1167. win.$.ajax = (params, ...args) => {
  1168. if (params.success) {
  1169. let _s = params.success;
  1170. params.success = (data, ...args) => _s(removeVast(data), ...args);
  1171. }
  1172. return _ajax(params, ...args);
  1173. };
  1174. } else if (win.getnextepisode && win.uppodEvent) {
  1175. log('Share-Serials.net');
  1176. scriptLander(
  1177. function () {
  1178. let _setInterval = win.setInterval,
  1179. _setTimeout = win.setTimeout;
  1180. win.setInterval = function (func) {
  1181. if (typeof func === 'function' && _toString(func).includes('_delay')) {
  1182. let intv = _setInterval.call(
  1183. this,
  1184. function () {
  1185. _setTimeout.call(
  1186. this,
  1187. function (intv) {
  1188. clearInterval(intv);
  1189. let timer = _document.querySelector('#timer');
  1190. if (timer)
  1191. timer.click();
  1192. }, 100, intv);
  1193. func.call(this);
  1194. }, 5
  1195. );
  1196.  
  1197. return intv;
  1198. }
  1199. return _setInterval.apply(this, arguments);
  1200. };
  1201. win.setTimeout = function (func) {
  1202. if (typeof func === 'function' && _toString(func).includes('adv_showed'))
  1203. return _setTimeout.call(this, func, 0);
  1204. return _setTimeout.apply(this, arguments);
  1205. };
  1206. }
  1207. );
  1208. } else if ('ADC' in win) {
  1209. log('vjs-creatives plugin in');
  1210. let replacer = (obj) => {
  1211. for (let name in obj)
  1212. if (typeof obj[name] === 'function')
  1213. obj[name] = () => null;
  1214. };
  1215. replacer(win.ADC);
  1216. replacer(win.currentAdSlot);
  1217. } else if ('Playerjs' in win) {
  1218. log('Playerjs');
  1219. win.Playerjs = new Proxy(win.Playerjs, {
  1220. construct(fn, args) {
  1221. let params = args[0];
  1222. if (params && typeof params === 'object') {
  1223. delete params.preroll;
  1224. params = removeVast(params);
  1225. Object.defineProperty(params, 'hasOwnProperty', {
  1226. value(...args) {
  1227. let res = _hasOwnProperty(this, ...args);
  1228. if (typeof args[0] === 'string' && args[0].startsWith('vast_') &&
  1229. res && params[args[0]]) {
  1230. _console.log(`Removed params.${args[0]}:`, params[args[0]]);
  1231. delete params[args[0]];
  1232. return false;
  1233. }
  1234. return res;
  1235. },
  1236. enumerable: false,
  1237. configurable: true
  1238. });
  1239. }
  1240. return _construct(fn, args);
  1241. }
  1242. });
  1243. }
  1244.  
  1245. UberVK: {
  1246. if (!inIFrame)
  1247. break UberVK;
  1248. let oddNames = 'HD' in win &&
  1249. !Object.getOwnPropertyNames(win).every(n => !n.startsWith('_0x'));
  1250. if (!oddNames)
  1251. break UberVK;
  1252. log('UberVK');
  1253. XMLHttpRequest.prototype.open = () => {
  1254. throw 404;
  1255. };
  1256. }
  1257. }, false
  1258. );
  1259. }
  1260.  
  1261. // Applies wrapper function on the current page and all newly created same-origin iframes
  1262. // This is used to prevent trick which allows to get fresh page API through newly created same-origin iframes
  1263. function deepWrapAPI(wrapper) {
  1264. let wrapped = new WeakSet();
  1265. const
  1266. log = (...args) => false && _console.log(...args),
  1267. _HTMLIFrameElement = HTMLIFrameElement.prototype,
  1268. isIFrameElement = _HTMLIFrameElement.isPrototypeOf.bind(_HTMLIFrameElement),
  1269. _contentWindow = Object.getOwnPropertyDescriptor(_HTMLIFrameElement, 'contentWindow'),
  1270. _get_contentWindow = _bindCall(_contentWindow.get);
  1271.  
  1272. function wrapAPI(root) {
  1273. if (!root || wrapped.has(root))
  1274. return;
  1275. wrapped.add(root);
  1276. try {
  1277. wrapper(isIFrameElement(root) ? _get_contentWindow(root) : root);
  1278. log('Wrapped API in', (root === win) ? "main window." : root);
  1279. } catch (e) {
  1280. log('Failed to wrap API in', (root === win) ? "main window." : root, '\n', e);
  1281. }
  1282. }
  1283.  
  1284. // wrap API on contentWindow access
  1285. const getter = {
  1286. apply(get, that, args) {
  1287. wrapAPI(that);
  1288. return _apply(get, that, args);
  1289. }
  1290. };
  1291. _contentWindow.get = new Proxy(_contentWindow.get, getter);
  1292. Object.defineProperty(_HTMLIFrameElement, 'contentWindow', _contentWindow);
  1293. // wrap API on contentDocument access
  1294. const _contentDocument = Object.getOwnPropertyDescriptor(_HTMLIFrameElement, 'contentDocument');
  1295. _contentDocument.get = new Proxy(_contentDocument.get, getter);
  1296. Object.defineProperty(_HTMLIFrameElement, 'contentDocument', _contentDocument);
  1297.  
  1298. // manual children objects traverser to avoid issues
  1299. // with calling querySelectorAll on wrong types of objects
  1300. const
  1301. _nodeType = _bindCall(Object.getOwnPropertyDescriptor(_Node, 'nodeType').get),
  1302. _childNodes = _bindCall(Object.getOwnPropertyDescriptor(_Node, 'childNodes').get),
  1303. _ELEMENT_NODE = _Node.ELEMENT_NODE,
  1304. _DOCUMENT_FRAGMENT_NODE = _Node.DOCUMENT_FRAGMENT_NODE;
  1305. const wrapFrames = root => {
  1306. if (_nodeType(root) !== _ELEMENT_NODE && _nodeType(root) !== _DOCUMENT_FRAGMENT_NODE)
  1307. return; // only process nodes which may contain an IFRAME or be one
  1308. if (isIFrameElement(root)) {
  1309. wrapAPI(root);
  1310. return;
  1311. }
  1312. for (let child of _childNodes(root))
  1313. wrapFrames(child);
  1314. };
  1315.  
  1316. // wrap API in a newly appended iframe objects
  1317. const wrappedAppendChild = new Proxy(_Node.appendChild, {
  1318. apply(fun, that, args) {
  1319. let res = _apply(fun, that, args);
  1320. wrapFrames(args[0]);
  1321. return res;
  1322. }
  1323. });
  1324. // ABP Freeze Element snippet replaces normal properties with getters without setters
  1325. const _Node_appendChild = Object.getOwnPropertyDescriptor(Node.prototype, 'appendChild');
  1326. if (_Node_appendChild.configurable) {
  1327. if (_Node_appendChild.value)
  1328. _Node_appendChild.value = wrappedAppendChild;
  1329. if (_Node_appendChild.get)
  1330. _Node_appendChild.get = () => wrappedAppendChild;
  1331. Object.defineProperty(_Node, 'appendChild', _Node_appendChild);
  1332. }
  1333.  
  1334. // wrap API in iframe objects created with innerHTML of element on page
  1335. const _innerHTML = Object.getOwnPropertyDescriptor(_Element, 'innerHTML');
  1336. _innerHTML.set = new Proxy(_innerHTML.set, {
  1337. apply(set, that, args) {
  1338. _apply(set, that, args);
  1339. if (_document.contains(that))
  1340. wrapFrames(that);
  1341. }
  1342. });
  1343. Object.defineProperty(_Element, 'innerHTML', _innerHTML);
  1344.  
  1345. wrapAPI(win);
  1346. }
  1347.  
  1348. // piguiqproxy.com / zmctrack.net circumvention and onerror callback prevention
  1349. scriptLander(
  1350. () => {
  1351. // onerror callback blacklist
  1352. let masks = [],
  1353. //blockAll = /(^|\.)(rutracker-org\.appspot\.com)$/,
  1354. isBlocked = url => masks.some(mask => mask.test(url)); // || blockAll.test(location.hostname);
  1355. for (let filter of [ // blacklist
  1356. // global
  1357. '/adv/www/',
  1358. // adservers
  1359. '||185.87.50.147^',
  1360. '||10root25.website^', '||24video.xxx^',
  1361. '||adlabs.ru^', '||adspayformymortgage.win^', '||aliru1.ru^', '||amgload.net^', '||aviabay.ru^',
  1362. '||bgrndi.com^', '||brokeloy.com^',
  1363. '||cdnjs-aws.ru^', '||cnamerutor.ru^',
  1364. '||directadvert.ru^', '||docfilms.info^', '||dreadfula.ru^', '||dsn-fishki.ru^',
  1365. '||et-cod.com^', '||et-code.ru^', '||etcodes.com^',
  1366. '||film-doma.ru^',
  1367. '||free-torrent.org^', '||free-torrent.pw^',
  1368. '||free-torrents.org^', '||free-torrents.pw^',
  1369. '||game-torrent.info^', '||gocdn.ru^',
  1370. '||hdkinoshka.com^', '||hghit.com^', '||hindcine.net^',
  1371. '||kinotochka.net^', '||kinott.com^', '||kinott.ru^',
  1372. '||klcheck.com^', '||kuveres.com^',
  1373. '||lepubs.com^', '||luxadv.com^', '||luxup.ru^', '||luxupcdna.com^',
  1374. '||marketgid.com^', '||mebablo.com^', '||mixadvert.com^', '||mxtads.com^',
  1375. '||nickhel.com^',
  1376. '||oconner.biz^', '||oconner.link^', '||octoclick.net^', '||octozoon.org^',
  1377. '||pigiuqproxy.com^', '||piguiqproxy.com^', '||pkpojhc.com^',
  1378. '||psma01.com^', '||psma02.com^', '||psma03.com^',
  1379. '||rcdn.pro^', '||recreativ.ru^', '||redtram.com^', '||regpole.com^',
  1380. '||rootmedia.ws^', '||ruttwind.com^', '||rutvind.com^',
  1381. '||skidl.ru^', '||smi2.net^', '||smcheck.org^',
  1382. '||torvind.com^', '||traffic-media.co^', '||trafmag.com^', '||trustjs.net^', '||ttarget.ru^',
  1383. '||u-dot-id-adtool.appspot.com^', '||utarget.ru^',
  1384. '||webadvert-gid.ru^', '||webadvertgid.ru^',
  1385. '||xxuhter.ru^',
  1386. '||yuiout.online^',
  1387. '||zmctrack.net^', '||zoom-film.ru^'
  1388. ])
  1389. masks.push(new RegExp(
  1390. filter.replace(/([\\/[\].+?(){}$])/g, '\\$1')
  1391. .replace(/\*/g, '.*?')
  1392. .replace(/\^(?!$)/g, '\\.?[^\\w%._-]')
  1393. .replace(/\^$/, '\\.?([^\\w%._-]|$)')
  1394. .replace(/^\|\|/, '^((ws|http)s?:|/)/+([^/.]+\\.)*?'),
  1395. 'i'));
  1396. // main script
  1397. deepWrapAPI(root => {
  1398. const
  1399. _defineProperty = root.Object.defineProperty,
  1400. _getOwnPropertyDescriptor = root.Object.getOwnPropertyDescriptor,
  1401. _dispatchEvent = _bindCall(root.EventTarget.prototype.dispatchEvent);
  1402.  
  1403. const dispatchCustomEvent = (
  1404. target, name, opts = {
  1405. bubble: false,
  1406. cancelable: false
  1407. }
  1408. ) => _dispatchEvent(target, new CustomEvent(name, opts));
  1409.  
  1410. {
  1411. // 'onerror' handler for scripts from blacklisted sources
  1412. const scriptMap = new WeakMap();
  1413. const _HTMLScriptElement = root.HTMLScriptElement,
  1414. _HTMLImageElement = root.HTMLImageElement;
  1415. const _get_tagName = _bindCall(_getOwnPropertyDescriptor(root.Element.prototype, 'tagName').get),
  1416. _get_scr_src = _bindCall(_getOwnPropertyDescriptor(_HTMLScriptElement.prototype, 'src').get),
  1417. _get_img_src = _bindCall(_getOwnPropertyDescriptor(_HTMLImageElement.prototype, 'src').get);
  1418. const _get_src = node => {
  1419. if (node instanceof _HTMLScriptElement)
  1420. return _get_scr_src(node);
  1421. if (node instanceof _HTMLImageElement)
  1422. return _get_img_src(node);
  1423. return undefined;
  1424. };
  1425. const _onerror = _getOwnPropertyDescriptor(root.HTMLElement.prototype, 'onerror');
  1426. _onerror.get = new Proxy(_onerror.get, {
  1427. apply(_fun, that) {
  1428. return scriptMap.get(that) || null;
  1429. }
  1430. });
  1431. _onerror.set = new Proxy(_onerror.set, {
  1432. apply(fun, that, args) {
  1433. let [callback] = args;
  1434. if (typeof callback !== 'function') {
  1435. scriptMap.delete(that);
  1436. _apply(fun, that, args);
  1437. return;
  1438. }
  1439. scriptMap.set(that, callback);
  1440. _apply(fun, that, [function () {
  1441. let src = _get_src(this);
  1442. if (isBlocked(src)) {
  1443. _console.trace(`Blocked "onerror" callback from ${_get_tagName(this)}: ${src}`);
  1444. return;
  1445. }
  1446. _apply(scriptMap.get(this), this, arguments);
  1447. }]);
  1448. }
  1449. });
  1450. _defineProperty(root.HTMLElement.prototype, 'onerror', _onerror);
  1451. }
  1452. // Simplistic WebSocket wrapper for Maxthon and Firefox before v58
  1453. // once again seems required in Google Chrome and similar browsers due to zmctrack.net -_-
  1454. if (_getOwnPropertyDescriptor(root, 'WebSocket'))
  1455. root.WebSocket = new Proxy(root.WebSocket, {
  1456. construct(ws, args) {
  1457. if (isBlocked(args[0])) {
  1458. _console.log('Blocked WS connection:', args[0]);
  1459. return {};
  1460. }
  1461. return _construct(ws, args);
  1462. }
  1463. });
  1464. // Block popular method to open a new window in Google Chrome by dispatching a custom click
  1465. // event on a newly created anchor with _blank target. Untrusted events must not open new windows.
  1466. const clickWhitelist = /^([^.]\.)*?nakarte\.me$/;
  1467. root.EventTarget.prototype.dispatchEvent = new Proxy(root.EventTarget.prototype.dispatchEvent, {
  1468. apply(fun, that, args) {
  1469. const e = args[0];
  1470. if (!clickWhitelist.test(win.location.hostname) &&
  1471. !e.isTrusted && e.type === 'click' && e.constructor.name === 'MouseEvent' &&
  1472. !that.parentNode && that.tagName === 'A' && that.target[0] === '_') {
  1473. _console.log('Blocked dispatching a click event on a parentless anchor:', that);
  1474. return;
  1475. }
  1476. return _apply(fun, that, args);
  1477. }
  1478. });
  1479. // blacklist of domains where all third-party requests are ignored
  1480. const ondomains = /(^|[/.@])oane\.ws($|[:/])/i;
  1481. // highly suspicious URLs
  1482. const suspicious = /^(https?:)?\/\/(?!(rutube|shazoo|worldoftanks)\.ru[:/])(csp-)?([a-z0-9]{6}){1,2}\.ru\//i;
  1483. const on_get_ban = /^(https?:)?\/\/(?!(rutube|shazoo|worldoftanks)\.ru[:/])(csp-)?([a-z0-9]{6}){1,2}\.ru\/([a-z0-9/]{40,}|[a-z0-9]{8,}|ad\/banner\/.+|show\/\?\d+=\d+&.+)$/i;
  1484. const on_post_ban = /^(https?:)?\/\/(?!(rutube|shazoo|worldoftanks)\.ru[:/])(csp-)?([a-z0-9]{6}){1,2}\.ru\/([a-z0-9]{6,})$/i;
  1485. const yandex_direct = /^(https?:)?\/\/([^.]+\.)??yandex(\.[a-z]{2,3}){1,2}\/(images\/[a-z0-9/_-]{40,}|jstracer?|j?clck\/.*|set\/s\/rsya-tag-users\/data(\?.*)?|static\/main\.js(\?.*)?)$/i;
  1486. const more_y_direct = /^(https?:)?\/\/((([^.]+\.)??(24smi\.org|(echo\.msk|drive2|kakprosto|razlozhi)\.ru)\/(.{290,}|[a-z0-9/_-]{100,}))|yastatic\.net\/.*?\/chunks\/promo\/.*)$/i;
  1487. const whitelist = /^(https?:)?\/\/yandex\.ru\/yobject$/;
  1488. const fabPatterns = /\/fuckadblock/i;
  1489.  
  1490. const blockedUrls = new Set();
  1491.  
  1492. function checkRequest(fname, method, url) {
  1493. let block = isBlocked(url) ||
  1494. ondomains.test(location.hostname) && !ondomains.test(url) ||
  1495. method !== 'POST' && on_get_ban.test(url) ||
  1496. method === 'POST' && on_post_ban.test(url) ||
  1497. yandex_direct.test(url) || more_y_direct.test(url);
  1498. let allow = block && whitelist.test(url) ||
  1499. // Fix for infinite load on Yandex Images: find image, open "other sizes and similar images" in a new tab, click on a preview of a similar image
  1500. (block && method === 'script.src' &&
  1501. root.location.pathname === '/images/search' && root.location.hostname.startsWith('yandex.') &&
  1502. url.startsWith('http') && url.includes('/images/')) || // Direct URLs are similar, but don't have protocol for some reason
  1503. (block && root.location.hostname === 'widgets.kinopoisk.ru' && url.includes('/static/main.js?')) ||
  1504. (block && !url.startsWith('http') && // drive2.ru hid a little CSS style in their requests which shows page content like this
  1505. (root.location.hostname === 'drive2.ru' || root.location.hostname.endsWith('.drive2.ru')));
  1506. if (allow) {
  1507. block = false;
  1508. _console.trace(`Allowed ${fname} ${method} request %o from %o`, url, root.location.href);
  1509. }
  1510. if (block) {
  1511. if (!blockedUrls.has(url)) // don't repeat log if the same URL were blocked more than once
  1512. _console.trace(`Blocked ${fname} ${method} request %o from %o`, url, root.location.href);
  1513. blockedUrls.add(url);
  1514. return true;
  1515. }
  1516. if (!allow && suspicious.test(url))
  1517. _console.trace(`Suspicious ${fname} ${method} request %o from %o`, url, root.location.href);
  1518. return false;
  1519. }
  1520.  
  1521. // workaround for broken searchbar on market.yandex.ru
  1522. const checkOnloadEvent = location.hostname.startsWith('market.yandex.');
  1523. const triggerLoadEvent = /^(https?:)?\/\/([^.]+\.)??yandex(\.[a-z]{2,3}){1,2}\/(j?clck\/.*)$/i;
  1524.  
  1525. // XHR Wrapper
  1526. const _proto = root.XMLHttpRequest && root.XMLHttpRequest.prototype;
  1527. if (_proto) {
  1528. const xhrStopList = new WeakSet();
  1529. const xhrDispatchLoadList = new WeakSet();
  1530. _proto.open = new Proxy(_proto.open, {
  1531. apply(fun, that, args) {
  1532. if (checkOnloadEvent && triggerLoadEvent.test(args[1]))
  1533. xhrDispatchLoadList.add(that);
  1534. if (checkRequest('xhr', ...args)) {
  1535. xhrStopList.add(that);
  1536. return;
  1537. }
  1538. return _apply(fun, that, args);
  1539. }
  1540. });
  1541. if (win.location.hostname.endsWith('.ukr.net') ||
  1542. win.location.hostname === 'ukr.net') {
  1543. // Technically useless code, but zmctrack's code on ukr.net runs before mine for some reason and is
  1544. // looking for 'skip_xhr_check' in this particular function's code and changes own behaviour
  1545. // depending on this... and somehow cease to work. Well, let it be here then for now.
  1546. const _open = _bindCall(_proto.open);
  1547. _proto.open = function open(...args) {
  1548. return _open(this, ...args); /*skip_xhr_check*/
  1549. };
  1550. }
  1551. const _DONE = _proto.DONE; // 4
  1552. const sendWrapper = {
  1553. apply(fun, that, args) {
  1554. if (xhrStopList.has(that)) {
  1555. if (that.readyState !== _DONE && xhrDispatchLoadList.has(that)) {
  1556. that.readyState = _DONE;
  1557. setTimeout(() => dispatchCustomEvent(that, 'load'), 0);
  1558. }
  1559. return null;
  1560. }
  1561. return _apply(fun, that, args);
  1562. }
  1563. };
  1564. ['send', 'setRequestHeader', 'getAllResponseHeaders'].forEach(
  1565. name => _proto[name] = new Proxy(_proto[name], sendWrapper)
  1566. );
  1567. // simulate readyState === 1 for blocked requests
  1568. const _readyState = Object.getOwnPropertyDescriptor(_proto, 'readyState');
  1569. _readyState.get = new Proxy(_readyState.get, {
  1570. apply(fun, that, args) {
  1571. return xhrStopList.has(that) ? 1 : _apply(fun, that, args);
  1572. }
  1573. });
  1574. Object.defineProperty(_proto, 'readyState', _readyState);
  1575. }
  1576.  
  1577. if (root.fetch)
  1578. root.fetch = new Proxy(root.fetch, {
  1579. apply(fun, that, args) {
  1580. let [url, opts] = args;
  1581. let method = opts && opts.method || 'GET';
  1582. if (typeof url === 'object' && 'headers' in url &&
  1583. 'url' in url && 'method' in url) // url instanceof Request
  1584. ({
  1585. url,
  1586. method
  1587. } = url);
  1588. if (checkRequest('fetch', method, url))
  1589. return new Promise(() => null);
  1590. return _apply(fun, that, args);
  1591. }
  1592. });
  1593.  
  1594. const _script_src = Object.getOwnPropertyDescriptor(root.HTMLScriptElement.prototype, 'src');
  1595. _script_src.set = new Proxy(_script_src.set, {
  1596. apply(fun, that, args) {
  1597. if (fabPatterns.test(args[0])) {
  1598. _console.trace('Blocked set script.src request:', args[0]);
  1599. deployFABStub(root);
  1600. setTimeout(() => dispatchCustomEvent(that, 'load'), 0);
  1601. return;
  1602. }
  1603. return checkRequest('set', 'script.src', args[0]) || _apply(fun, that, args);
  1604. }
  1605. });
  1606. Object.defineProperty(root.HTMLScriptElement.prototype, 'src', _script_src);
  1607.  
  1608. const adregain_pattern = /ggg==" alt="advertisement"/;
  1609. if (root.self !== root.top) // in IFrame
  1610. root.document.write = new Proxy(root.document.write, {
  1611. apply(fun, that, args) {
  1612. if (adregain_pattern.test(args[0])) {
  1613. _console.log('Skipped AdRegain frame.');
  1614. args[0] = '';
  1615. }
  1616. return _apply(fun, that, args);
  1617. }
  1618. });
  1619. });
  1620. }, deepWrapAPI
  1621. );
  1622.  
  1623. // === Helper functions ===
  1624.  
  1625. // function to search and remove nodes by content
  1626. // selector - standard CSS selector to define set of nodes to check
  1627. // words - regular expression to check content of the suspicious nodes
  1628. // params - object with multiple extra parameters:
  1629. // .log - display log in the console
  1630. // .hide - set display to none instead of removing from the page
  1631. // .parent - parent node to remove if content is found in the child node
  1632. // .siblings - number of simling nodes to remove (excluding text nodes)
  1633. function scissors(selector, words, scope, params) {
  1634. const logger = (...args) => {
  1635. if (params.log) _console.log(...args);
  1636. };
  1637. const scHide = node => {
  1638. let style = _getAttribute(node, 'style') || '',
  1639. hide = ';display:none!important;';
  1640. if (style.indexOf(hide) < 0)
  1641. _setAttribute(node, 'style', style + hide);
  1642. };
  1643.  
  1644. if (!scope.contains(_document.body))
  1645. logger('[s] scope', scope);
  1646. let remFunc = (params.hide ? scHide : node => node.parentNode.removeChild(node)),
  1647. iterFunc = (params.siblings > 0 ? 'nextElementSibling' : 'previousElementSibling'),
  1648. toRemove = [],
  1649. siblings;
  1650. for (let node of scope.querySelectorAll(selector)) {
  1651. // drill up to a parent node if specified, break if not found
  1652. if (params.parent) {
  1653. let old = node;
  1654. node = node.closest(params.parent);
  1655. if (node === null || node.contains(scope)) {
  1656. logger('[s] went out of scope with', old);
  1657. continue;
  1658. }
  1659. }
  1660. logger('[s] processing', node);
  1661. if (toRemove.includes(node))
  1662. continue;
  1663. if (words.test(node.innerHTML)) {
  1664. // skip node if already marked for removal
  1665. logger('[s] marked for removal');
  1666. toRemove.push(node);
  1667. // add multiple nodes if defined more than one sibling
  1668. siblings = Math.abs(params.siblings) || 0;
  1669. while (siblings) {
  1670. node = node[iterFunc];
  1671. if (!node) break; // can't go any further - exit
  1672. logger('[s] adding sibling node', node);
  1673. toRemove.push(node);
  1674. siblings -= 1;
  1675. }
  1676. }
  1677. }
  1678. const toSkip = [];
  1679. toSkip.checkNode = node => !toRemove.every(other => other === node || !node.contains(other));
  1680. for (let node of toRemove)
  1681. if (toSkip.checkNode(node))
  1682. toSkip.push(node);
  1683. if (toRemove.length)
  1684. logger(`[s] proceeding with ${params.hide?'hide':'removal'} of`, toRemove, `skip`, toSkip);
  1685. for (let node of toRemove)
  1686. if (!toSkip.includes(node))
  1687. remFunc(node);
  1688. }
  1689.  
  1690. // function to perform multiple checks if ads inserted with a delay
  1691. // by default does 30 checks withing a 3 seconds unless nonstop mode specified
  1692. // also does 1 extra check when a page completely loads
  1693. // selector and words - passed dow to scissors
  1694. // params - object with multiple extra parameters:
  1695. // .log - display log in the console
  1696. // .root - selector to narrow down scope to scan;
  1697. // .observe - if true then check will be performed continuously;
  1698. // Other parameters passed down to scissors.
  1699. function gardener(selector, words, params) {
  1700. let logger = (...args) => {
  1701. if (params.log) _console.log(...args);
  1702. };
  1703. params = params || {};
  1704. logger(`[gardener] selector: '${selector}' detector: ${words} options: ${JSON.stringify(params)}`);
  1705. let scope;
  1706. let globalScope = [_de];
  1707. let domLoaded = false;
  1708. let getScope = root => root ? _de.querySelectorAll(root) : globalScope;
  1709. let onevent = e => {
  1710. logger(`[gardener] cleanup on ${Object.getPrototypeOf(e)} "${e.type}"`);
  1711. for (let node of scope)
  1712. scissors(selector, words, node, params);
  1713. };
  1714. let repeater = n => {
  1715. if (!domLoaded && n) {
  1716. setTimeout(repeater, 500, n - 1);
  1717. scope = getScope(params.root);
  1718. if (!scope) // exit if the root element is not present on the page
  1719. return 0;
  1720. onevent({
  1721. type: 'Repeater'
  1722. });
  1723. }
  1724. };
  1725. repeater(20);
  1726. _document.addEventListener(
  1727. 'DOMContentLoaded', (e) => {
  1728. domLoaded = true;
  1729. // narrow down scope to a specific element
  1730. scope = getScope(params.root);
  1731. if (!scope) // exit if the root element is not present on the page
  1732. return 0;
  1733. logger('[g] scope', scope);
  1734. // add observe mode if required
  1735. if (params.observe) {
  1736. let params = {
  1737. childList: true,
  1738. subtree: true
  1739. };
  1740. let observer = new MutationObserver(
  1741. function (ms) {
  1742. for (let m of ms)
  1743. if (m.addedNodes.length)
  1744. onevent(m);
  1745. }
  1746. );
  1747. for (let node of scope)
  1748. observer.observe(node, params);
  1749. logger('[g] observer enabled');
  1750. }
  1751. onevent(e);
  1752. }, false);
  1753. // wait for a full page load to do one extra cut
  1754. win.addEventListener('load', onevent, false);
  1755. }
  1756.  
  1757. // wrap popular methods to open a new tab to catch specific behaviours
  1758. function createWindowOpenWrapper(openFunc) {
  1759. const parser = _createElement('a');
  1760. const openWhitelist = (url, parent) => {
  1761. parser.href = url;
  1762. return parser.hostname === 'www.imdb.com' || parser.hostname === 'www.kinopoisk.ru' ||
  1763. parent.hostname === 'radikal.ru' && url === undefined;
  1764. };
  1765.  
  1766. function redefineOpen(root) {
  1767. if ('open' in root)
  1768. root.open = new Proxy(root.open, {
  1769. apply(fun, that, args) {
  1770. if (openWhitelist(args[0], location)) {
  1771. _console.log('Whitelisted popup:', ...args);
  1772. return _apply(fun, that, args);
  1773. }
  1774. return openFunc(...args);
  1775. }
  1776. });
  1777. }
  1778. redefineOpen(win);
  1779.  
  1780. const createElementWrapper = {
  1781. apply(fun, that, args) {
  1782. const el = _apply(fun, that, args);
  1783. // redefine window.open in first-party frames
  1784. if (el instanceof HTMLIFrameElement || el instanceof HTMLObjectElement)
  1785. el.addEventListener('load', (e) => {
  1786. try {
  1787. redefineOpen(e.target.contentWindow);
  1788. } catch (ignore) {}
  1789. }, false);
  1790. return el;
  1791. }
  1792. };
  1793.  
  1794. function redefineCreateElement(obj) {
  1795. for (let root of [obj.document, _Document])
  1796. if ('createElement' in root) {
  1797. root.createElement = new Proxy(root.createElement, createElementWrapper);
  1798. nt.defineOn(root, 'createElement', new Proxy(createElement, {}), 'Document.prototype.');
  1799. }
  1800. }
  1801. redefineCreateElement(win);
  1802.  
  1803. // wrap window.open in newly added first-party frames
  1804. const wrappedAppendChild = new Proxy(_Node.appendChild, {
  1805. apply(fun, that, args) {
  1806. let el = _apply(fun, that, args);
  1807. if (el instanceof HTMLIFrameElement)
  1808. try {
  1809. redefineOpen(el.contentWindow);
  1810. redefineCreateElement(el.contentWindow);
  1811. } catch (ignore) {}
  1812. return el;
  1813. }
  1814. });
  1815. // ABP Freeze Element snippet replaces normal properties with getters without setters
  1816. const _Node_appendChild = Object.getOwnPropertyDescriptor(Node.prototype, 'appendChild');
  1817. if (_Node_appendChild.configurable) {
  1818. if (_Node_appendChild.value)
  1819. _Node_appendChild.value = wrappedAppendChild;
  1820. if (_Node_appendChild.get)
  1821. _Node_appendChild.get = () => wrappedAppendChild;
  1822. Object.defineProperty(_Node, 'appendChild', _Node_appendChild);
  1823. }
  1824. }
  1825.  
  1826. // Function to catch and block various methods to open a new window with 3rd-party content.
  1827. // Some advertisement networks went way past simple window.open call to circumvent default popup protection.
  1828. // This funciton blocks window.open, ability to restore original window.open from an IFRAME object,
  1829. // ability to perform an untrusted (not initiated by user) click on a link, click on a link without a parent
  1830. // node or simply a link with piece of javascript code in the HREF attribute.
  1831. function preventPopups() {
  1832. // call sandbox-me if in iframe and not whitelisted
  1833. if (inIFrame) {
  1834. win.top.postMessage({
  1835. name: 'sandbox-me',
  1836. href: win.location.href
  1837. }, '*');
  1838. return;
  1839. }
  1840.  
  1841. scriptLander(() => {
  1842. let open = (...args) => {
  1843. '[native code]';
  1844. _console.trace('Site attempted to open a new window', ...args);
  1845. return {
  1846. document: nt.proxy({
  1847. write: nt.func({}, 'write'),
  1848. writeln: nt.func({}, 'writeln')
  1849. }),
  1850. location: nt.proxy({})
  1851. };
  1852. };
  1853.  
  1854. createWindowOpenWrapper(open);
  1855.  
  1856. _console.log('Popup prevention enabled.');
  1857. }, nullTools, createWindowOpenWrapper);
  1858. }
  1859.  
  1860. // Helper function to close background tab if site opens itself in a new tab and then
  1861. // loads a 3rd-party page in the background one (thus performing background redirect).
  1862. function preventPopunders() {
  1863. // create "close_me" event to call high-level window.close()
  1864. let eventName = `close_me_${Math.random().toString(36).substr(2)}`;
  1865. let callClose = () => {
  1866. _console.log('close call');
  1867. window.close();
  1868. };
  1869. window.addEventListener(eventName, callClose, true);
  1870.  
  1871. scriptLander(() => {
  1872. // get host of a provided URL with help of an anchor object
  1873. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  1874. let parseURL = _document.createElement('A');
  1875. let getHost = url => {
  1876. parseURL.href = url;
  1877. return parseURL.hostname;
  1878. };
  1879. // site went to a new tab and attempts to unload
  1880. // call for high-level close through event
  1881. let closeWindow = () => window.dispatchEvent(new CustomEvent(eventName, {}));
  1882. // check is URL local or goes to different site
  1883. let isLocal = (url) => {
  1884. if (url === location.pathname || url === location.href)
  1885. return true; // URL points to current pathname or full address
  1886. let host = getHost(url);
  1887. let site = location.hostname;
  1888. return host !== '' && // URLs with unusual protocol may have empty 'host'
  1889. (site === host || site.endsWith(`.${host}`) || host.endsWith(`.${site}`));
  1890. };
  1891.  
  1892. let _open = window.open.bind(window);
  1893. let open = (...args) => {
  1894. '[native code]';
  1895. let url = args[0];
  1896. if (url && isLocal(url))
  1897. window.addEventListener('beforeunload', closeWindow, true);
  1898. return _open(...args);
  1899. };
  1900.  
  1901. createWindowOpenWrapper(open);
  1902.  
  1903. _console.log("Background redirect prevention enabled.");
  1904. }, `let eventName="${eventName}"`, nullTools, createWindowOpenWrapper);
  1905. }
  1906.  
  1907. // Mix between check for popups and popunders
  1908. // Significantly more agressive than both and can't be used as universal solution
  1909. function preventPopMix() {
  1910. if (inIFrame) {
  1911. win.top.postMessage({
  1912. name: 'sandbox-me',
  1913. href: win.location.href
  1914. }, '*');
  1915. return;
  1916. }
  1917.  
  1918. // create "close_me" event to call high-level window.close()
  1919. let eventName = `close_me_${Math.random().toString(36).substr(2)}`;
  1920. let callClose = () => {
  1921. _console.log('close call');
  1922. window.close();
  1923. };
  1924. window.addEventListener(eventName, callClose, true);
  1925.  
  1926. scriptLander(() => {
  1927. let _open = window.open,
  1928. parseURL = _document.createElement('A');
  1929. // get host of a provided URL with help of an anchor object
  1930. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  1931. let getHost = (url) => {
  1932. parseURL.href = url;
  1933. return parseURL.host;
  1934. };
  1935. // site went to a new tab and attempts to unload
  1936. // call for high-level close through event
  1937. let closeWindow = () => {
  1938. _open(window.location, '_self');
  1939. window.dispatchEvent(new CustomEvent(eventName, {}));
  1940. };
  1941. // check is URL local or goes to different site
  1942. function isLocal(url) {
  1943. let loc = window.location;
  1944. if (url === loc.pathname || url === loc.href)
  1945. return true; // URL points to current pathname or full address
  1946. let host = getHost(url),
  1947. site = loc.host;
  1948. if (host === '')
  1949. return false; // URLs with unusual protocol may have empty 'host'
  1950. if (host.length > site.length)
  1951. [site, host] = [host, site];
  1952. return site.includes(host, site.length - host.length);
  1953. }
  1954.  
  1955. // add check for redirect for 5 seconds, then disable it
  1956. function checkRedirect() {
  1957. window.addEventListener('beforeunload', closeWindow, true);
  1958. setTimeout(closeWindow => window.removeEventListener('beforeunload', closeWindow, true), 5000, closeWindow);
  1959. }
  1960.  
  1961. function open(url, name) {
  1962. '[native code]';
  1963. if (url && isLocal(url) && (!name || name === '_blank')) {
  1964. _console.trace('Suspicious local new window', ...arguments);
  1965. checkRedirect();
  1966. /* jshint validthis: true */
  1967. return _open.apply(this, arguments);
  1968. }
  1969. _console.trace('Blocked attempt to open a new window', ...arguments);
  1970. return {
  1971. document: {
  1972. write() {},
  1973. writeln() {}
  1974. }
  1975. };
  1976. }
  1977.  
  1978. function clickHandler(e) {
  1979. let link = e.target,
  1980. url = link.href || '';
  1981. if (e.targetParentNode && e.isTrusted || link.target !== '_blank') {
  1982. _console.log('Link', link, 'were created dinamically, but looks fine.');
  1983. return true;
  1984. }
  1985. if (isLocal(url) && link.target === '_blank') {
  1986. _console.log('Suspicious local link', link);
  1987. checkRedirect();
  1988. return;
  1989. }
  1990. _console.log('Blocked suspicious click on a link', link);
  1991. e.stopPropagation();
  1992. e.preventDefault();
  1993. }
  1994.  
  1995. createWindowOpenWrapper(open, clickHandler);
  1996.  
  1997. _console.log("Mixed popups prevention enabled.");
  1998. }, `let eventName="${eventName}"`, createWindowOpenWrapper);
  1999. }
  2000. // External listener for case when site known to open popups were loaded in iframe
  2001. // It will sandbox any iframe which will send message 'forbid.popups' (preventPopups sends it)
  2002. // Some sites replace frame's window.location with data-url to run in clean context
  2003. if (!inIFrame) window.addEventListener(
  2004. 'message',
  2005. function (e) {
  2006. if (!e.data || e.data.name !== 'sandbox-me' || !e.data.href)
  2007. return;
  2008. let src = e.data.href;
  2009. for (let frame of _document.querySelectorAll('iframe'))
  2010. if (frame.contentWindow === e.source) {
  2011. if (frame.hasAttribute('sandbox')) {
  2012. if (!frame.sandbox.contains('allow-popups'))
  2013. return; // exit frame since it's already sandboxed and popups are blocked
  2014. // remove allow-popups if frame already sandboxed
  2015. frame.sandbox.remove('allow-popups');
  2016. } else
  2017. // set sandbox mode for troublesome frame and allow scripts, forms and a few other actions
  2018. // technically allowing both scripts and same-origin allows removal of the sandbox attribute,
  2019. // but to apply content must be reloaded and this script will re-apply it in the result
  2020. frame.setAttribute('sandbox', 'allow-forms allow-scripts allow-presentation allow-top-navigation allow-same-origin');
  2021. _console.log('Disallowed popups from iframe', frame);
  2022.  
  2023. // reload frame content to apply restrictions
  2024. if (!src) {
  2025. src = frame.src;
  2026. _console.log('Unable to get current iframe location, reloading from src', src);
  2027. } else
  2028. _console.log('Reloading iframe with URL', src);
  2029. frame.src = 'about:blank';
  2030. frame.src = src;
  2031. }
  2032. }, false
  2033. );
  2034.  
  2035. const evalPatternYandex = /{exports:{},id:r,loaded:!1}|containerId:(.|\r|\n)+params:/,
  2036. evalPatternGeneric = /_0x|location\s*?=|location.href\s*?=|location.assign\(|open\(/i;
  2037.  
  2038. function selectiveEval(...patterns) {
  2039. let fullLog = false;
  2040. if (patterns[patterns.length - 1] === true) {
  2041. fullLog = true;
  2042. patterns.length = patterns.length - 1;
  2043. }
  2044. if (patterns.length === 0)
  2045. patterns.push(evalPatternGeneric);
  2046. win.eval = new Proxy(win.eval, {
  2047. apply(fun, that, args) {
  2048. if (patterns.some(pattern => pattern.test(args[0]))) {
  2049. _console[fullLog ? 'trace' : 'log'](`Skipped eval ${fullLog ? args[0] : args[0].slice(0, 512)}${fullLog ? '' : '\u2026'}`);
  2050. return null;
  2051. }
  2052. try {
  2053. if (fullLog)
  2054. _console.trace(`eval ${args[0]}`);
  2055. return _apply(fun, that, args);
  2056. } catch (e) {
  2057. _console.error('Crash source:', args[0]);
  2058. throw e;
  2059. }
  2060. }
  2061. });
  2062. }
  2063. selectiveEval.toString = new Proxy(selectiveEval.toString, {
  2064. apply(...args) {
  2065. return `${_apply(...args)} const evalPatternYandex = ${evalPatternYandex}, evalPatternGeneric = ${evalPatternGeneric}`;
  2066. }
  2067. });
  2068.  
  2069. // hides cookies by pattern and attempts to remove them if they already set
  2070. // also prevents setting new versions of such cookies
  2071. function selectiveCookies(scPattern = '', opts = {}) {
  2072. let patterns = scPattern.split('|');
  2073. if (patterns[0] !== '~default') {
  2074. // Google Analytics cookies
  2075. patterns.push('_g(at?|id)|__utm[a-z]');
  2076. // Yandex ABP detection cookies
  2077. patterns.push('bltsr|blcrm');
  2078. } else
  2079. patterns.shift();
  2080. let blacklist = new RegExp(`(^|;\\s?)(${patterns.join('|')})($|=)`);
  2081.  
  2082. const root = opts.root || win;
  2083. const _root_Document = Object.getPrototypeOf(root.HTMLDocument.prototype);
  2084. const _doc_proto = ('cookie' in _root_Document) ? _root_Document : Object.getPrototypeOf(root.document);
  2085. const _cookie = Object.getOwnPropertyDescriptor(_doc_proto, 'cookie');
  2086. const _set_cookie = _bindCall(_cookie.set);
  2087.  
  2088. const removeLog = (cookie) => {
  2089. let strings = [`${cookie.name}=${cookie.value}`];
  2090. if (cookie.domain)
  2091. strings.push(`domain=${cookie.domain}`);
  2092. if (cookie.path)
  2093. strings.push(`path=${cookie.path}`);
  2094. if (cookie.sameSite !== 'unspecified')
  2095. strings.push(`sameSite=${cookie.sameSite}`);
  2096. for (let name of ['httpOnly', 'hostOnly', 'secure', 'session'])
  2097. if (cookie[name]) strings.push(name);
  2098. _console.log(`Removed cookie: ${strings.join('; ')}`);
  2099. };
  2100.  
  2101. let skipTM = true;
  2102. const asyncCookieCleaner = () => {
  2103. GM.cookie.list({
  2104. url: location.href
  2105. }).then(cookies => {
  2106. if (!cookies) return;
  2107. if (skipTM) {
  2108. cookies = cookies.filter(x => !x.name.startsWith('TM_'));
  2109. skipTM = false;
  2110. }
  2111. for (let cookie of cookies)
  2112. if (blacklist.test(cookie.name)) {
  2113. if (skipTM && cookie.name)
  2114. continue;
  2115. GM.cookie.delete(cookie);
  2116. removeLog(cookie);
  2117. }
  2118. });
  2119. };
  2120.  
  2121. const useOldPass = (() => {
  2122. // returns true if GM version <= 4.10
  2123. let v = GM.info.version.split('.').map(x => x - 0);
  2124. return v[0] < 4 || v[0] === 4 && v[1] <= 10 && v[2] === undefined || GM.info.scriptHandler !== 'Tampermonkey';
  2125. })();
  2126.  
  2127. const getName = (cookie) => cookie && cookie.indexOf('=') ? /^(.+?)=/.exec(cookie)[1] : cookie;
  2128.  
  2129. const removeCookie = (cookie, that) => {
  2130. const expireCookie = (name, domain) => {
  2131. domain = domain ? `;domain=${domain.join('.')}` : '';
  2132. _set_cookie(that, `${name}=;Max-Age=0;path=/${domain}`);
  2133. _set_cookie(that, `${name}=;Max-Age=0;path=/${domain.replace('=', '=.')}`);
  2134. };
  2135. const name = getName(cookie);
  2136. const domain = that.location.hostname.split('.');
  2137.  
  2138. expireCookie(name);
  2139. while (domain.length > 1) {
  2140. try {
  2141. expireCookie(name, domain);
  2142. } catch (e) {
  2143. _console.error(e);
  2144. }
  2145. domain.shift();
  2146. }
  2147. _console.log('Removing existing cookie:', cookie);
  2148. };
  2149.  
  2150. if (_cookie) {
  2151. // skip setting unwanted cookies
  2152. _cookie.set = new Proxy(_cookie.set, {
  2153. apply(fun, that, args) {
  2154. if (useOldPass) {
  2155. let cookie = args[0];
  2156. if (blacklist.test(getName(cookie))) {
  2157. _console.log('Ignored cookie: %s', cookie);
  2158. removeCookie(cookie, that);
  2159. return;
  2160. }
  2161. }
  2162. _apply(fun, that, args);
  2163. asyncCookieCleaner();
  2164. return true;
  2165. }
  2166. });
  2167. // hide unwanted cookies from site
  2168. _cookie.get = new Proxy(_cookie.get, {
  2169. apply(fun, that, args) {
  2170. asyncCookieCleaner();
  2171. let res = _apply(fun, that, args);
  2172. if (blacklist.test(res)) {
  2173. let stack = [];
  2174. for (let cookie of res.split(/;\s?/))
  2175. if (!blacklist.test(getName(cookie)))
  2176. stack.push(cookie);
  2177. else
  2178. if (useOldPass) removeCookie(cookie, that);
  2179. res = stack.join('; ');
  2180. }
  2181. return res;
  2182. }
  2183. });
  2184. Object.defineProperty(_doc_proto, 'cookie', _cookie);
  2185. _console.log('Active cookies:', root.document.cookie);
  2186. }
  2187. }
  2188.  
  2189. // Locates a node with specific text in Russian
  2190. // Uses table of substitutions for similar letters
  2191. let selectNodeByTextContent = (() => {
  2192. let subs = {
  2193. // english & greek
  2194. 'А': 'AΑ',
  2195. 'В': 'BΒ',
  2196. 'Г': 'Γ',
  2197. 'Е': 'EΕ',
  2198. 'З': '3',
  2199. 'К': 'KΚ',
  2200. 'М': 'MΜ',
  2201. 'Н': 'HΗ',
  2202. 'О': 'OΟ',
  2203. 'П': 'Π',
  2204. 'Р': 'PΡ',
  2205. 'С': 'C',
  2206. 'Т': 'T',
  2207. 'Ф': 'Φ',
  2208. 'Х': 'XΧ'
  2209. };
  2210. let regExpBuilder = text => new RegExp(
  2211. text.toUpperCase()
  2212. .split('')
  2213. .map(function (e) {
  2214. return `${e in subs ? `[${e}${subs[e]}]` : (e === ' ' ? '\\s+' : e)}[\u200b\u200c\u200d]*`;
  2215. })
  2216. .join(''),
  2217. 'i');
  2218. let reMap = {};
  2219. return (re, opts = {
  2220. root: _document.body
  2221. }) => {
  2222. if (!re.test) {
  2223. if (!reMap[re])
  2224. reMap[re] = regExpBuilder(re);
  2225. re = reMap[re];
  2226. }
  2227.  
  2228. for (let child of opts.root.children)
  2229. if (re.test(child.textContent)) {
  2230. if (opts.shallow)
  2231. return child;
  2232. opts.root = child;
  2233. return selectNodeByTextContent(re, opts) || child;
  2234. }
  2235. };
  2236. })();
  2237.  
  2238. // webpackJsonp filter
  2239. function webpackJsonpFilter(blacklist, log = false) {
  2240. function wrapPush(webpack) {
  2241. let _push = webpack.push.bind(webpack);
  2242. Object.defineProperty(webpack, 'push', {
  2243. get() {
  2244. return _push;
  2245. },
  2246. set(vl) {
  2247. _push = new Proxy(vl, {
  2248. apply(fun, that, args) {
  2249. wrapper: {
  2250. if (!(args[0] instanceof Array))
  2251. break wrapper;
  2252. let mainName;
  2253. if (args[0][2] instanceof Array && args[0][2][0] instanceof Array)
  2254. mainName = args[0][2][0][0];
  2255. let funs = args[0][1];
  2256. if (!(funs instanceof Object && !(funs instanceof Array)))
  2257. break wrapper;
  2258. const noopFunc = (name, text) => () => _console.log(`Skip webpack ${name}`, text);
  2259. for (let name in funs) {
  2260. if (typeof funs[name] !== 'function')
  2261. continue;
  2262. if (blacklist.test(_toString(funs[name])) && name !== mainName)
  2263. funs[name] = noopFunc(name, log ? _toString(funs[name]) : '');
  2264. }
  2265. }
  2266. _console.log('webpack.push()');
  2267. return _apply(fun, that, args);
  2268. }
  2269. });
  2270. return true;
  2271. }
  2272. });
  2273. return webpack;
  2274. }
  2275. let _webpackJsonp = wrapPush([]);
  2276. Object.defineProperty(win, 'webpackJsonp', {
  2277. get() {
  2278. return _webpackJsonp;
  2279. },
  2280. set(vl) {
  2281. if (vl === _webpackJsonp)
  2282. return;
  2283. _console.log('new webpackJsonp', vl);
  2284. _webpackJsonp = wrapPush(vl);
  2285. }
  2286. });
  2287. }
  2288.  
  2289. // JSON filter
  2290. // removeList - list of paths divided by space to remove
  2291. // checkList - optional list of paths divided by space to check presence of before removal
  2292. const jsonFilter = (function jsonFilterModule() {
  2293. const _log = (() => {
  2294. if (!jsf.AccessStatistics)
  2295. return () => null;
  2296. const counter = {};
  2297. const counterToString = () => Object.entries(counter).map(a => `\n * ${a.join(': ')}`).join('');
  2298. let lock = 0;
  2299. return async function _log(path) {
  2300. counter[path] = (counter[path] || 0) + 1;
  2301. lock++;
  2302. setTimeout(() => {
  2303. lock--;
  2304. if (lock === 0)
  2305. _console.log('JSON filters:', counterToString());
  2306. }, 3333);
  2307. };
  2308. })();
  2309.  
  2310. const isObjecty = o => (typeof o === 'object' || typeof o === 'function') && o !== null;
  2311.  
  2312. function parsePath(root, path) {
  2313. let pos;
  2314. pos = path.indexOf('.');
  2315. for (let name; pos > 0;) {
  2316. name = path.slice(0, pos);
  2317. if (!isObjecty(root[name]))
  2318. break;
  2319. root = root[name];
  2320. path = path.slice(pos + 1);
  2321. pos = path.indexOf('.');
  2322. }
  2323. return [pos < 0 && _hasOwnProperty(root, path), root, path];
  2324. }
  2325.  
  2326. const filterList = [];
  2327.  
  2328. function filter(result) {
  2329. if (!isObjecty(result))
  2330. return result;
  2331.  
  2332. const pathNotInObject = path => !(parsePath(result, path)[0]);
  2333. const removePathInObject = path => {
  2334. let [exist, root, name] = parsePath(result, path);
  2335. if (exist) {
  2336. delete root[name];
  2337. _log(path);
  2338. }
  2339. };
  2340. for (let list of filterList) {
  2341. if (list.check && list.check.some(pathNotInObject))
  2342. return result;
  2343. list.remove.forEach(removePathInObject);
  2344. }
  2345.  
  2346. return result;
  2347. }
  2348.  
  2349.  
  2350. let wrapped = false;
  2351.  
  2352. function jsonFilter(removeList, checkList) {
  2353. filterList.push({
  2354. remove: removeList.split(/\s/),
  2355. check: checkList ? checkList.split(/\s/) : undefined
  2356. });
  2357.  
  2358. if (wrapped) return;
  2359. wrapped = true;
  2360.  
  2361. win.JSON.parse = new Proxy(win.JSON.parse, {
  2362. apply(fun, that, args) {
  2363. return filter(_apply(fun, that, args));
  2364. }
  2365. });
  2366.  
  2367. win.Response.prototype.json = new Proxy(win.Response.prototype.json, {
  2368. apply(fun, that, args) {
  2369. let promise = _apply(fun, that, args);
  2370. promise.then(res => filter(res));
  2371. return promise;
  2372. }
  2373. });
  2374. }
  2375. jsonFilter.toString = () => `const jsonFilter = (${jsonFilterModule.toString()})()`;
  2376. return jsonFilter;
  2377. })();
  2378.  
  2379. // === Scripts for specific domains ===
  2380.  
  2381. const scripts = {
  2382. // prevent popups and redirects block
  2383. // Popups
  2384. preventPopups: {
  2385. other: 'biqle.ru, chaturbate.com, dfiles.ru, eporner.eu, hentaiz.org, mirrorcreator.com, online-multy.ru' +
  2386. 'radikal.ru, rumedia.ws, tapehub.tech, thepiratebay.org, unionpeer.com, zippyshare.com',
  2387. now: preventPopups
  2388. },
  2389. // Popunders (background redirect)
  2390. preventPopunders: {
  2391. other: 'lostfilm-online.ru, mediafire.com, megapeer.org, megapeer.ru, perfectgirls.net',
  2392. now: preventPopunders
  2393. },
  2394.  
  2395. // PopMix (both types of popups encountered on site)
  2396. 'openload.co': {
  2397. other: 'oload.tv, oload.info, openload.co.com',
  2398. now() {
  2399. if (inIFrame) {
  2400. nt.define('BetterJsPop', {
  2401. add(a, b) {
  2402. _console.trace('BetterJsPop.add(%o, %o)', a, b);
  2403. },
  2404. config(o) {
  2405. _console.trace('BetterJsPop.config(%o)', o);
  2406. },
  2407. Browser: {
  2408. isChrome: true
  2409. }
  2410. });
  2411. nt.define('isSandboxed', nt.func(null, 'isSandboxed'));
  2412. nt.define('adblock', false);
  2413. nt.define('adblock2', false);
  2414. } else preventPopMix();
  2415. }
  2416. },
  2417.  
  2418. 'turbobit.net': preventPopMix,
  2419.  
  2420. 'tapochek.net': () => {
  2421. // workaround for moradu.com/apu.php load error handler script, not sure which ad network is this
  2422. let _appendChild = Object.getOwnPropertyDescriptor(_Node, 'appendChild');
  2423. let _appendChild_value = _appendChild.value;
  2424. _appendChild.value = function appendChild(node) {
  2425. if (this === _document.body)
  2426. if ((node instanceof HTMLScriptElement || node instanceof HTMLStyleElement) &&
  2427. /^https?:\/\/[0-9a-f]{15}\.com\/\d+(\/|\.css)$/.test(node.src) ||
  2428. node instanceof HTMLDivElement && node.style.zIndex > 900000 &&
  2429. node.style.backgroundImage.includes('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'))
  2430. throw '...eenope!';
  2431. return _appendChild_value.apply(this, arguments);
  2432. };
  2433. Object.defineProperty(_Node, 'appendChild', _appendChild);
  2434.  
  2435. // disable window focus tricks and changing location
  2436. let focusHandlerName = /\WfocusAchieved\(/;
  2437. let _setInterval = win.setInterval;
  2438. win.setInterval = (...args) => {
  2439. if (args.length && focusHandlerName.test(_toString(args[0]))) {
  2440. _console.log('skip setInterval for', ...args);
  2441. return -1;
  2442. }
  2443. return _setInterval(...args);
  2444. };
  2445. let _addEventListener = win.addEventListener;
  2446. win.addEventListener = function (...args) {
  2447. if (args.length && args[0] === 'focus' && focusHandlerName.test(_toString(args[1]))) {
  2448. _console.log('skip addEventListener for', ...args);
  2449. return undefined;
  2450. }
  2451. return _addEventListener.apply(this, args);
  2452. };
  2453.  
  2454. // generic popup prevention
  2455. preventPopups();
  2456. },
  2457.  
  2458. // = other ======================================================================================
  2459.  
  2460. '1tv.ru': {
  2461. other: 'mediavitrina.ru',
  2462. now: () => scriptLander(() => {
  2463. nt.define('EUMPAntiblockConfig', nt.proxy({
  2464. url: '//www.1tv.ru/favicon.ico'
  2465. }));
  2466. nt.define('Object.prototype.disableSeek', nt.func(undefined, 'disableSeek'));
  2467. //nt.define('preroll', undefined);
  2468.  
  2469. let _EUMP;
  2470. const _EUMP_set = x => {
  2471. if (x === _EUMP)
  2472. return true;
  2473. let _plugins = x.plugins;
  2474. Object.defineProperty(x, 'plugins', {
  2475. enumerable: true,
  2476. get() {
  2477. return _plugins;
  2478. },
  2479. set(vl) {
  2480. if (vl === _plugins)
  2481. return true;
  2482. nt.defineOn(vl, 'antiblock', function (player, opts) {
  2483. const antiblock = nt.proxy({
  2484. opts: opts,
  2485. readyState: 'ready',
  2486. isEUMPPlugin: true,
  2487. detected: nt.func(false, 'antiblock.detected'),
  2488. currentWeight: nt.func(0, 'antiblock.currentWeight')
  2489. });
  2490. player.antiblock = antiblock;
  2491. return antiblock;
  2492. }, 'EUMP.plugins.');
  2493. _plugins = vl;
  2494. }
  2495. });
  2496. _EUMP = x;
  2497. return true;
  2498. };
  2499. if ('EUMP' in win)
  2500. _EUMP_set(win.EUMP);
  2501. Object.defineProperty(win, 'EUMP', {
  2502. enumerable: true,
  2503. get() {
  2504. return _EUMP;
  2505. },
  2506. set: _EUMP_set
  2507. });
  2508.  
  2509. let _EUMPVGTRK;
  2510. const _EUMPVGTRK_set = x => {
  2511. if (x === _EUMPVGTRK)
  2512. return true;
  2513. if (x && x.prototype) {
  2514. if ('generatePrerollUrls' in x.prototype)
  2515. nt.defineOn(x.prototype, 'generatePrerollUrls', nt.func(null, 'EUMPVGTRK.generatePrerollUrls'), 'EUMPVGTRK.prototype.', {
  2516. enumerable: false
  2517. });
  2518. if ('sendAdsEvent' in x.prototype)
  2519. nt.defineOn(x.prototype, 'sendAdsEvent', nt.func(null, 'EUMPVGTRK.sendAdsEvent'), 'EUMPVGTRK.prototype.', {
  2520. enumerable: false
  2521. });
  2522. }
  2523. _EUMPVGTRK = x;
  2524. return true;
  2525. };
  2526. if ('EUMPVGTRK' in win)
  2527. _EUMPVGTRK_set(win.EUMPVGTRK);
  2528. Object.defineProperty(win, 'EUMPVGTRK', {
  2529. enumerable: true,
  2530. get() {
  2531. return _EUMPVGTRK;
  2532. },
  2533. set: _EUMPVGTRK_set
  2534. });
  2535. }, nullTools)
  2536. },
  2537.  
  2538. '24smi.org': () => scriptLander(() => selectiveCookies('has_adblock'), selectiveCookies),
  2539.  
  2540. '2picsun.ru': {
  2541. other: 'pics2sun.ru, 3pics-img.ru',
  2542. now() {
  2543. Object.defineProperty(navigator, 'userAgent', {
  2544. value: 'googlebot'
  2545. });
  2546. }
  2547. },
  2548.  
  2549. '4pda.ru': {
  2550. now() {
  2551. // https://greasyfork.org/en/scripts/14470-4pda-unbrender
  2552. const isForum = location.pathname.startsWith('/forum/'),
  2553. remove = node => (node && node.parentNode.removeChild(node)),
  2554. hide = node => (node && (node.style.display = 'none'));
  2555.  
  2556. selectiveCookies('viewpref');
  2557. abortExecution.inlineScript('document.querySelector', {
  2558. pattern: /\(document(,window)?\);/
  2559. });
  2560.  
  2561. function cleaner(log) {
  2562. HeaderAds: {
  2563. // hide ads above HEADER
  2564. let nav = _document.querySelector('.menu-main-item');
  2565. while (nav && (nav.parentNode !== _de))
  2566. if (!nav.parentNode.querySelector('article, .container[itemtype$="Article"]'))
  2567. nav = nav.parentNode;
  2568. else break;
  2569. if (!nav || (nav.parentNode === _de)) {
  2570. if (log) _console.warn('Unable to locate header element');
  2571. break HeaderAds;
  2572. }
  2573. if (log) _console.log('Processing header:', nav);
  2574. for (let itm of nav.parentNode.children)
  2575. if (itm !== nav)
  2576. hide(itm);
  2577. else break;
  2578. }
  2579.  
  2580. FixNavMenu: {
  2581. // hide ad link from the navigation
  2582. let ad = _document.querySelector('.menu-main-item > a > svg');
  2583. if (!ad) {
  2584. if (log) _console.warn('Unable to locate menu ad item');
  2585. break FixNavMenu;
  2586. } else {
  2587. ad = ad.parentNode.parentNode;
  2588. hide(ad);
  2589. }
  2590. }
  2591.  
  2592. SidebarAds: {
  2593. // remove ads from sidebar
  2594. let aside = _document.querySelectorAll('[class]:not([id]) > [id]:not([class]) > :first-child + :last-child:not(.v-panel)');
  2595. if (!aside.length) {
  2596. if (log) _console.warn('Unable to locate sidebar');
  2597. break SidebarAds;
  2598. }
  2599. let post;
  2600. for (let side of aside) {
  2601. if (log) _console.log('Processing potential sidebar:', side);
  2602. for (let itm of Array.from(side.children)) {
  2603. post = itm.classList.contains('post');
  2604. if (post) continue;
  2605. if (itm.querySelector('iframe') || !itm.children.length)
  2606. remove(itm);
  2607. let script = itm.querySelector('script');
  2608. if (itm.querySelector('a[target="_blank"] > img') ||
  2609. script && script.src === '' && (script.type === 'text/javascript' || !script.type) &&
  2610. script.textContent.includes('document'))
  2611. hide(itm);
  2612. }
  2613. }
  2614. }
  2615. }
  2616.  
  2617. const cln = setInterval(() => cleaner(false), 50);
  2618.  
  2619. // hide banner next to logo
  2620. if (isForum)
  2621. createStyle('div[class]:not([id]) tr[valign="top"] > td:last-child { display: none !important }');
  2622. // clean page
  2623. window.addEventListener(
  2624. 'DOMContentLoaded',
  2625. function () {
  2626. clearInterval(cln);
  2627. const width = () => win.innerWidth || _de.clientWidth || _document.body.clientWidth || 0,
  2628. height = () => win.innerHeight || _de.clientHeight || _document.body.clientHeight || 0;
  2629.  
  2630. if (isForum) {
  2631. // hide banner next to logo
  2632. //let itm = _document.querySelector('#logostrip');
  2633. //if (itm) hide(itm.parentNode.nextSibling);
  2634. // clear background in the download frame
  2635. if (location.pathname.startsWith('/forum/dl/')) {
  2636. let setBackground = node => _setAttribute(
  2637. node,
  2638. 'style', (_getAttribute(node, 'style') || '') +
  2639. ';background-color:#4ebaf6!important'
  2640. );
  2641. setBackground(_document.body);
  2642. for (let itm of _document.querySelectorAll('body > div'))
  2643. if (!itm.querySelector('.dw-fdwlink, .content') && !itm.classList.contains('footer'))
  2644. remove(itm);
  2645. else
  2646. setBackground(itm);
  2647. }
  2648. // exist from DOMContentLoaded since the rest is not for forum
  2649. return;
  2650. }
  2651.  
  2652. cleaner(false);
  2653.  
  2654. _document.body.setAttribute('style', (_document.body.getAttribute('style') || '') + ';background-color:#E6E7E9!important');
  2655.  
  2656. let extra = 'background-image:none!important;background-color:transparent!important',
  2657. fakeStyles = new WeakMap(),
  2658. styleProxy = {
  2659. get(target, prop) {
  2660. return fakeStyles.get(target)[prop] || target[prop];
  2661. },
  2662. set(target, prop, value) {
  2663. let fakeStyle = fakeStyles.get(target);
  2664. ((prop in fakeStyle) ? fakeStyle : target)[prop] = value;
  2665. return true;
  2666. }
  2667. };
  2668. for (let itm of _document.querySelectorAll('[id]:not(A), A')) {
  2669. if (!(itm.offsetWidth > 0.95 * width() &&
  2670. itm.offsetHeight > 0.85 * height()))
  2671. continue;
  2672. if (itm.tagName !== 'A') {
  2673. fakeStyles.set(itm.style, {
  2674. 'backgroundImage': itm.style.backgroundImage,
  2675. 'backgroundColor': itm.style.backgroundColor
  2676. });
  2677.  
  2678. try {
  2679. Object.defineProperty(itm, 'style', {
  2680. value: new Proxy(itm.style, styleProxy),
  2681. enumerable: true
  2682. });
  2683. } catch (e) {
  2684. _console.log('Unable to protect style property.', e);
  2685. }
  2686.  
  2687. _setAttribute(itm, 'style', `${(_getAttribute(itm, 'style') || '')};${extra}`);
  2688. }
  2689. if (itm.tagName === 'A')
  2690. _setAttribute(itm, 'style', 'display:none!important');
  2691. }
  2692. }
  2693. );
  2694. }
  2695. },
  2696.  
  2697. 'adhands.ru': () => scriptLander(() => {
  2698. try {
  2699. let _adv;
  2700. Object.defineProperty(win, 'adv', {
  2701. get() {
  2702. return _adv;
  2703. },
  2704. set(val) {
  2705. _console.log('Blocked advert on adhands.ru.');
  2706. nt.defineOn(val, 'advert', '', 'adv.');
  2707. _adv = val;
  2708. }
  2709. });
  2710. } catch (ignore) {
  2711. if (!win.adv)
  2712. _console.log('Unable to locate advert on adhands.ru.');
  2713. else {
  2714. _console.log('Blocked advert on adhands.ru.');
  2715. nt.define('adv.advert', '');
  2716. }
  2717. }
  2718. }, nullTools),
  2719.  
  2720. 'all-episodes.org': () => {
  2721. nt.define('perROS', 0); // blocks access when = 1
  2722. nt.define('idm', -1); // blocks quality when >= 0
  2723. nt.define('detdet', nt.func(null, 'detdet'));
  2724. // skip check for ads
  2725. win.setTimeout = new Proxy(win.setTimeout, {
  2726. apply(fun, that, args) {
  2727. if (args[0]) {
  2728. const text = _toString(args[0]);
  2729. if (text.includes('#bip') || text.includes('#advtss')) {
  2730. _console.log('Skipped check.');
  2731. return;
  2732. }
  2733. }
  2734. return _apply(fun, that, args);
  2735. }
  2736. });
  2737. // wrap player to prevent some events and interactions
  2738. let _playerInstance = win.playerInstance;
  2739. Object.defineProperty(win, 'playerInstance', {
  2740. get() {
  2741. return _playerInstance;
  2742. },
  2743. set(vl) {
  2744. _console.log('player', vl);
  2745. vl.on = new Proxy(vl.on, {
  2746. apply(fun, that, args) {
  2747. if (/^(ad[A-Z]|before(Play|Complete))/.test(args[0]))
  2748. return;
  2749. return _apply(fun, that, args);
  2750. }
  2751. });
  2752. vl.getAdBlock = () => false;
  2753. _playerInstance = vl;
  2754. }
  2755. });
  2756. },
  2757.  
  2758. 'allhentai.ru': () => {
  2759. preventPopups();
  2760. scriptLander(() => {
  2761. selectiveEval();
  2762. let _onerror = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onerror');
  2763. if (!_onerror)
  2764. return;
  2765. _onerror.set = (...args) => _console.log(args[0].toString());
  2766. Object.defineProperty(HTMLElement.prototype, 'onerror', _onerror);
  2767. }, selectiveEval);
  2768. },
  2769.  
  2770. 'allmovie.pro': {
  2771. other: 'rufilmtv.org',
  2772. dom() {
  2773. // pretend to be Android to make site use different played for ads
  2774. if (isSafari)
  2775. return;
  2776. Object.defineProperty(navigator, 'userAgent', {
  2777. get() {
  2778. return 'Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19';
  2779. },
  2780. enumerable: true
  2781. });
  2782. }
  2783. },
  2784.  
  2785. 'ati.su': () => scriptLander(() => {
  2786. nt.define('Object.prototype.advManager', nt.proxy({}, 'advManager'));
  2787. }),
  2788.  
  2789. 'audioportal.su': {
  2790. now() {
  2791. createStyle('#blink2 { display: none !important }');
  2792. },
  2793. dom() {
  2794. let links = _document.querySelectorAll('a[onclick*="clickme("]');
  2795. if (!links) return;
  2796. for (let link of links)
  2797. win.clickme(link);
  2798. }
  2799. },
  2800.  
  2801. 'auto.ru': () => {
  2802. let words = /Реклама|Яндекс.Директ|yandex_ad_/;
  2803. let userAdsListAds = (
  2804. '.listing-list > .listing-item,' +
  2805. '.listing-item_type_fixed.listing-item'
  2806. );
  2807. let catalogAds = (
  2808. 'div[class*="layout_catalog-inline"],' +
  2809. 'div[class$="layout_horizontal"]'
  2810. );
  2811. let otherAds = (
  2812. '.advt_auto,' +
  2813. '.sidebar-block,' +
  2814. '.pager-listing + div[class],' +
  2815. '.card > div[class][style],' +
  2816. '.sidebar > div[class],' +
  2817. '.main-page__section + div[class],' +
  2818. '.listing > tbody'
  2819. );
  2820. gardener(userAdsListAds, words, {
  2821. root: '.listing-wrap',
  2822. observe: true
  2823. });
  2824. gardener(catalogAds, words, {
  2825. root: '.catalog__page,.content__wrapper',
  2826. observe: true
  2827. });
  2828. gardener(otherAds, words);
  2829. },
  2830.  
  2831. 'avito.ru': () => scriptLander(() => selectiveCookies('abp|cmtchd|crookie|is_adblock'), selectiveCookies),
  2832.  
  2833. 'di.fm': () => scriptLander(() => {
  2834. let log = false;
  2835. // wrap global app object to catch registration of specific modules
  2836. let _di = win.di;
  2837. Object.defineProperty(win, 'di', {
  2838. get() {
  2839. return _di;
  2840. },
  2841. set(vl) {
  2842. if (vl === _di)
  2843. return;
  2844. if (log) _console.trace('di =', vl);
  2845. _di = new Proxy(vl, {
  2846. set(di, name, vl) {
  2847. if (vl === di[name])
  2848. return true;
  2849. if (name === 'app') {
  2850. if (log) _console.trace(`di.${name} =`, vl);
  2851. if (!('module' in vl))
  2852. return;
  2853. vl.module = new Proxy(vl.module, {
  2854. apply(module, that, args) {
  2855. if (/Wall|Banner|Detect|WebplayerApp\.Ads/.test(args[0])) {
  2856. let name = args[0];
  2857. if (log) _console.log('wrap', name, 'module');
  2858. if (typeof args[1] === 'function')
  2859. args[1] = new Proxy(args[1], {
  2860. apply(fun, that, args) {
  2861. if (args[0]) // module object
  2862. args[0].start = () => _console.log('Skipped start of', name);
  2863. return Reflect.apply(fun, that, args);
  2864. }
  2865. });
  2866. } // else log && _console.log('loading module', args[0]);
  2867. if (args[0] === 'Modals' && typeof args[1] === 'function') {
  2868. if (log) _console.log('wrap', name, 'module');
  2869. args[1] = new Proxy(args[1], {
  2870. apply(fun, that, args) {
  2871. if ('commands' in args[1] && 'setHandlers' in args[1].commands &&
  2872. !Object.hasOwnProperty.call(args[1].commands, 'setHandlers')) {
  2873. let _commands = args[1].commands;
  2874. _commands.setHandlers = new Proxy(_commands.setHandlers, {
  2875. apply(fun, that, args) {
  2876. const noopFunc = name => () => _console.log('Skipped', name, 'window');
  2877. for (let name in args[0])
  2878. if (name === 'modal:streaminterrupt' ||
  2879. name === 'modal:midroll')
  2880. args[0][name] = noopFunc(name);
  2881. delete _commands.setHandlers;
  2882. return Reflect.apply(fun, that, args);
  2883. }
  2884. });
  2885. }
  2886. return Reflect.apply(fun, that, args);
  2887. }
  2888. });
  2889. }
  2890. return Reflect.apply(module, that, args);
  2891. }
  2892. });
  2893. }
  2894. di[name] = vl;
  2895. }
  2896. });
  2897. }
  2898. });
  2899. // don't send errorception logs
  2900. Object.defineProperty(win, 'onerror', {
  2901. set(vl) {
  2902. if (log) _console.trace('Skipped global onerror callback:', vl);
  2903. }
  2904. });
  2905. }),
  2906.  
  2907. 'draug.ru': {
  2908. other: 'vargr.ru',
  2909. now: () => scriptLander(() => {
  2910. if (location.pathname === '/pop.html')
  2911. win.close();
  2912. createStyle({
  2913. '#timer_1': {
  2914. display: 'none !important'
  2915. },
  2916. '#timer_2': {
  2917. display: 'block !important'
  2918. }
  2919. });
  2920. let _contentWindow = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, 'contentWindow');
  2921. let _get_contentWindow = _bindCall(_contentWindow.get);
  2922. _contentWindow.get = function () {
  2923. let res = _get_contentWindow(this);
  2924. if (res.location.href === 'about:blank')
  2925. res.document.write = (...args) => _console.log('Skipped iframe.write(', ...args, ')');
  2926. return res;
  2927. };
  2928. Object.defineProperty(HTMLIFrameElement.prototype, 'contentWindow', _contentWindow);
  2929. }),
  2930. dom() {
  2931. let list = _querySelectorAll('div[id^="yandex_rtb_"], .adsbygoogle');
  2932. list.forEach(node => _console.log('Removed:', node.parentNode.parentNode.removeChild(node.parentNode)));
  2933. }
  2934. },
  2935.  
  2936. 'drive2.ru': () => {
  2937. gardener('.c-block:not([data-metrika="recomm"]),.o-grid__item', />Реклама<\//i);
  2938. scriptLander(() => {
  2939. selectiveCookies();
  2940. let _d2;
  2941. Object.defineProperty(win, 'd2', {
  2942. get() {
  2943. return _d2;
  2944. },
  2945. set(vl) {
  2946. if (vl === _d2)
  2947. return true;
  2948. _d2 = new Proxy(vl, {
  2949. set(target, prop, val) {
  2950. if (['brandingRender', 'dvReveal', '__dv'].includes(prop))
  2951. val = () => null;
  2952. target[prop] = val;
  2953. return true;
  2954. }
  2955. });
  2956. }
  2957. });
  2958. // obfuscated Yandex.Direct
  2959. nt.define('Object.prototype.initYaDirect', undefined);
  2960. }, nullTools, selectiveCookies);
  2961. },
  2962.  
  2963. 'echo.msk.ru': () => scriptLander(() => {
  2964. selectiveCookies();
  2965. selectiveEval(evalPatternYandex, /^document\.write/, /callAdblock/);
  2966. }, selectiveEval, selectiveCookies),
  2967.  
  2968. 'eurogamer.tld': {
  2969. other: 'metabomb.net, usgamer.net',
  2970. now: () => scriptLander(() => {
  2971. abortExecution.inlineScript('_sp_');
  2972. selectiveCookies('sp');
  2973. }, selectiveCookies, abortExecution)
  2974. },
  2975.  
  2976. 'fastpic.ru': () => {
  2977. // Had to obfuscate property name to avoid triggering anti-obfuscation on greasyfork.org -_- (Exception 403012)
  2978. nt.define(`_0x${'4955'}`, []);
  2979. },
  2980.  
  2981. 'fishki.net': () => {
  2982. scriptLander(() => {
  2983. const fishki = {};
  2984. const adv = nt.proxy({
  2985. afterAdblockCheck: nt.func(null, 'fishki.afterAdblockCheck'),
  2986. refreshFloat: nt.func(null, 'fishki.refreshFloat')
  2987. });
  2988. nt.defineOn(fishki, 'adv', adv, 'fishki.');
  2989. nt.defineOn(fishki, 'is_adblock', false, 'fishki.');
  2990. nt.define('fishki', fishki);
  2991. nt.define('Object.prototype.detect', nt.func(undefined, 'detect'));
  2992. win.Object.defineProperty = new Proxy(win.Object.defineProperty, {
  2993. apply(fun, that, args) {
  2994. if (['is_adblock', 'adv'].includes(args[1]) || args[0] === adv)
  2995. return;
  2996. return _apply(fun, that, args);
  2997. }
  2998. });
  2999. }, nullTools);
  3000. gardener('.drag_list > .drag_element, .list-view > .paddingtop15, .post-wrap', /543769|Новости\sпартнеров|Полезная\sреклама/);
  3001. },
  3002.  
  3003. 'forbes.com': () => {
  3004. createStyle(['fbs-ad[ad-id], .top-ad-container, .fbs-ad-wrapper, .footer-ad-labeling, .ad-rail, .ad-unit { display: none !important; }']);
  3005. nt.define('Object.prototype.isAdLight', true);
  3006. nt.define('Object.prototype.initializeAd', nt.func(undefined, '?.initializeAd'));
  3007. win.getComputedStyle = new Proxy(win.getComputedStyle, {
  3008. apply(fun, that, args) {
  3009. let res = _apply(fun, that, args);
  3010. if (res.display === 'none')
  3011. nt.defineOn(res, 'display', 'block', 'getComputedStyle().');
  3012. if (res.visibility === 'hidden')
  3013. nt.defineOn(res, 'visibility', 'visible', 'getComputedStyle().');
  3014. return res;
  3015. }
  3016. });
  3017. win.CSSStyleDeclaration.prototype.getPropertyValue = new Proxy(win.CSSStyleDeclaration.prototype.getPropertyValue, {
  3018. apply(fun, that, args) {
  3019. let res = _apply(fun, that, args);
  3020. if (args[0] === 'display' && res === 'none')
  3021. return 'block';
  3022. if (args[0] === 'visibility' && res === 'hidden')
  3023. return 'visible';
  3024. return res;
  3025. }
  3026. });
  3027. },
  3028.  
  3029. 'friends.in.ua': () => scriptLander(() => {
  3030. Object.defineProperty(win, 'need_warning', {
  3031. get() {
  3032. return 0;
  3033. },
  3034. set() {}
  3035. });
  3036. }),
  3037.  
  3038. 'gamerevolution.com': () => {
  3039. const _clientHeight = Object.getOwnPropertyDescriptor(_Element, 'clientHeight');
  3040. _clientHeight.get = new Proxy(_clientHeight.get, {
  3041. apply(...args) {
  3042. return _apply(...args) || 1;
  3043. }
  3044. });
  3045. Object.defineProperty(_Element, 'clientHeight', _clientHeight);
  3046.  
  3047. const toReplace = [
  3048. 'blockerDetected', 'disableDetected', 'hasAdBlocker',
  3049. 'hasBlockerFlag', 'hasDisabledAdBlocker', 'hasBlocker'
  3050. ];
  3051. win.Object.defineProperty = new Proxy(win.Object.defineProperty, {
  3052. apply(fun, that, args) {
  3053. if (toReplace.includes(args[1])) {
  3054. args[2] = {
  3055. value() {
  3056. return false;
  3057. }
  3058. };
  3059. console.log(args);
  3060. }
  3061. return _apply(fun, that, args);
  3062. }
  3063. });
  3064. },
  3065.  
  3066. 'gamersheroes.com': () => abortExecution.inlineScript('document.createElement', {
  3067. pattern: /window\[\w+\(\[(\d+,?\s?)+\],\s?\w+\)\]/
  3068. }),
  3069.  
  3070. 'gidonline.club': () => createStyle('.tray > div[style] {display: none!important}'),
  3071.  
  3072. 'glav.su': () => scriptLander(() => {
  3073. abortExecution.inlineScript('EventTarget.prototype.addEventListener', {
  3074. pattern: /nosferatu/
  3075. });
  3076. }, abortExecution),
  3077.  
  3078. 'gorodrabot.ru': () => scriptLander(() => {
  3079. abortExecution.onGet('Object.prototype.yaads');
  3080. abortExecution.onGet('Object.prototype.initYaDirect');
  3081. }, abortExecution),
  3082.  
  3083. 'hdgo.cc': {
  3084. other: '46.30.43.38, couber.be',
  3085. now() {
  3086. (new MutationObserver(
  3087. ms => {
  3088. let m, node;
  3089. for (m of ms)
  3090. for (node of m.addedNodes)
  3091. if (node.tagName instanceof HTMLScriptElement && _getAttribute(node, 'onerror') !== null)
  3092. node.removeAttribute('onerror');
  3093. }
  3094. )).observe(_document.documentElement, {
  3095. childList: true,
  3096. subtree: true
  3097. });
  3098. }
  3099. },
  3100.  
  3101. 'gamepur.com': () => {
  3102. nt.define('ga', nt.func(null, 'ga'));
  3103. win.Object.defineProperty = new Proxy(win.Object.defineProperty, {
  3104. apply(fun, that, args) {
  3105. if (typeof args[1] === 'string' &&
  3106. (args[1] === 'hasAdblocker' || args[1] === 'blockerDetected'))
  3107. throw new ReferenceError(`${args[1]} is not defined`);
  3108. return Reflect.apply(fun, that, args);
  3109. }
  3110. });
  3111. },
  3112.  
  3113. 'gismeteo.tld': {
  3114. now: () => scriptLander(() => {
  3115. gardener('div > script', /AdvManager/i, {
  3116. observe: true,
  3117. parent: 'div'
  3118. });
  3119. }, nullTools, selectiveCookies)
  3120. },
  3121.  
  3122. 'hdrezka.ag': () => {
  3123. Object.defineProperty(win, 'ab', {
  3124. value: false,
  3125. enumerable: true
  3126. });
  3127. gardener('div[id][onclick][onmouseup][onmousedown]', /onmouseout/i);
  3128. },
  3129.  
  3130. 'hqq.tv': () => scriptLander(() => {
  3131. // disable anti-debugging in hqq.tv player
  3132. let isObfuscated = text => /[^a-z0-9]([a-z0-9]{1,2}\.[a-z0-9]{1,2}\(|[a-z0-9]{4}\.[a-z]\(\d+\)|[a-z0-9]\[[a-z0-9]{1,2}\]\[[a-z0-9]{1,2}\])/i.test(text);
  3133. deepWrapAPI(root => {
  3134. // skip obfuscated stuff and a few other calls
  3135. let _setInterval = root.setInterval,
  3136. _setTimeout = root.setTimeout;
  3137. root.setInterval = (...args) => {
  3138. let fun = args[0];
  3139. if (typeof fun === 'function') {
  3140. let text = _toString(fun),
  3141. skip = text.includes('check();') || isObfuscated(text);
  3142. _console.trace('setInterval', text, 'skip', skip);
  3143. if (skip) return -1;
  3144. }
  3145. return _setInterval.apply(this, args);
  3146. };
  3147. let wrappedST = new WeakSet();
  3148. root.setTimeout = (...args) => {
  3149. let fun = args[0];
  3150. if (typeof fun === 'function') {
  3151. let text = _toString(fun),
  3152. skip = fun.name === 'check' || isObfuscated(text);
  3153. if (!wrappedST.has(fun)) {
  3154. _console.trace('setTimeout', text, 'skip', skip);
  3155. wrappedST.add(fun);
  3156. }
  3157. if (skip) return;
  3158. }
  3159. return _setTimeout.apply(this, args);
  3160. };
  3161. // skip 'debugger' call
  3162. let _eval = root.eval;
  3163. root.eval = text => {
  3164. if (typeof text === 'string' && text.includes('debugger;')) {
  3165. _console.trace('skip eval', text);
  3166. return;
  3167. }
  3168. _eval(text);
  3169. };
  3170. // Prevent RegExpt + toString trick
  3171. let _proto;
  3172. try {
  3173. _proto = root.RegExp.prototype;
  3174. } catch (ignore) {
  3175. return;
  3176. }
  3177. let _RE_tS = Object.getOwnPropertyDescriptor(_proto, 'toString');
  3178. let _RE_tSV = _RE_tS.value || _RE_tS.get();
  3179. Object.defineProperty(_proto, 'toString', {
  3180. enumerable: _RE_tS.enumerable,
  3181. configurable: _RE_tS.configurable,
  3182. get() {
  3183. return _RE_tSV;
  3184. },
  3185. set(val) {
  3186. _console.trace('Attempt to change toString for', this, 'with', _toString(val));
  3187. }
  3188. });
  3189. });
  3190. }, deepWrapAPI),
  3191.  
  3192. 'hideip.me': {
  3193. now: () => scriptLander(() => {
  3194. let _innerHTML = Object.getOwnPropertyDescriptor(_Element, 'innerHTML');
  3195. let _set_innerHTML = _innerHTML.set;
  3196. let _innerText = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'innerText');
  3197. let _get_innerText = _innerText.get;
  3198. let div = _document.createElement('div');
  3199. _innerHTML.set = function (...args) {
  3200. _set_innerHTML.call(div, args[0].replace('i', 'a'));
  3201. if (args[0] && /[рp][еe]кл/.test(_get_innerText.call(div)) ||
  3202. /(\d\d\d?\.){3}\d\d\d?:\d/.test(_get_innerText.call(this))) {
  3203. _console.log('Anti-Adblock killed.');
  3204. return true;
  3205. }
  3206. _set_innerHTML.apply(this, args);
  3207. };
  3208. Object.defineProperty(_Element, 'innerHTML', _innerHTML);
  3209. Object.defineProperty(win, 'adblock', {
  3210. get() {
  3211. return false;
  3212. },
  3213. set() {},
  3214. enumerable: true
  3215. });
  3216. let _$ = {};
  3217. let _$_map = new WeakMap();
  3218. let _gOPD = Object.getOwnPropertyDescriptor(Object, 'getOwnPropertyDescriptor');
  3219. let _val_gOPD = _gOPD.value;
  3220. _gOPD.value = function (...args) {
  3221. let _res = _val_gOPD.apply(this, args);
  3222. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery')) {
  3223. delete _res.get;
  3224. delete _res.set;
  3225. _res.value = win[args[1]];
  3226. }
  3227. return _res;
  3228. };
  3229. Object.defineProperty(Object, 'getOwnPropertyDescriptor', _gOPD);
  3230. let getJQWrap = (n) => {
  3231. let name = n;
  3232. return {
  3233. enumerable: true,
  3234. get() {
  3235. return _$[name];
  3236. },
  3237. set(x) {
  3238. if (_$_map.has(x)) {
  3239. _$[name] = _$_map.get(x);
  3240. return true;
  3241. }
  3242. if (x === _$.$ || x === _$.jQuery) {
  3243. _$[name] = x;
  3244. return true;
  3245. }
  3246. _$[name] = new Proxy(x, {
  3247. apply(t, o, args) {
  3248. let _res = t.apply(o, args);
  3249. if (_$_map.has(_res.is))
  3250. _res.is = _$_map.get(_res.is);
  3251. else {
  3252. let _is = _res.is;
  3253. _res.is = function (...args) {
  3254. if (args[0] === ':hidden')
  3255. return false;
  3256. return _is.apply(this, args);
  3257. };
  3258. _$_map.set(_is, _res.is);
  3259. }
  3260. return _res;
  3261. }
  3262. });
  3263. _$_map.set(x, _$[name]);
  3264. return true;
  3265. }
  3266. };
  3267. };
  3268. Object.defineProperty(win, '$', getJQWrap('$'));
  3269. Object.defineProperty(win, 'jQuery', getJQWrap('jQuery'));
  3270. let _dP = Object.defineProperty;
  3271. Object.defineProperty = function (...args) {
  3272. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery'))
  3273. return undefined;
  3274. return _dP.apply(this, args);
  3275. };
  3276. })
  3277. },
  3278.  
  3279. 'igra-prestoloff.cx': () => scriptLander(() => {
  3280. /*jslint evil: true */ // yes, evil, I know
  3281. let _write = _document.write.bind(_document);
  3282. /*jslint evil: false */
  3283. nt.define('document.write', t => {
  3284. let id = t.match(/jwplayer\("(\w+)"\)/i);
  3285. if (id && id[1])
  3286. return _write(`<div id="${id[1]}"></div>${t}`);
  3287. return _write('');
  3288. }, {
  3289. enumerable: true
  3290. });
  3291. }),
  3292.  
  3293. 'imageban.ru': () => {
  3294. Object.defineProperty(win, 'V7x1J', {
  3295. get() {
  3296. return null;
  3297. }
  3298. });
  3299. },
  3300.  
  3301. 'inoreader.com': () => scriptLander(() => {
  3302. let i = setInterval(() => {
  3303. if ('adb_detected' in win) {
  3304. win.adb_detected = () => win.adb_not_detected();
  3305. clearInterval(i);
  3306. }
  3307. }, 10);
  3308. _document.addEventListener('DOMContentLoaded', () => clearInterval(i), false);
  3309. }),
  3310.  
  3311. 'it-actual.ru': () => scriptLander(() => {
  3312. abortExecution.onAll('blocked');
  3313. abortExecution.onGet('nsg');
  3314. }, abortExecution),
  3315.  
  3316. 'ivi.ru': () => {
  3317. let _xhr_open = win.XMLHttpRequest.prototype.open;
  3318. win.XMLHttpRequest.prototype.open = function (method, url, ...args) {
  3319. if (typeof url === 'string')
  3320. if (url.endsWith('/track'))
  3321. return;
  3322. return _xhr_open.call(this, method, url, ...args);
  3323. };
  3324. let _responseText = Object.getOwnPropertyDescriptor(XMLHttpRequest.prototype, 'responseText');
  3325. let _responseText_get = _responseText.get;
  3326. _responseText.get = function () {
  3327. if (this.__responseText__)
  3328. return this.__responseText__;
  3329. let res = _responseText_get.apply(this, arguments);
  3330. let o;
  3331. try {
  3332. if (res)
  3333. o = JSON.parse(res);
  3334. } catch (ignore) {}
  3335. let changed = false;
  3336. if (o && o.result) {
  3337. if (o.result instanceof Array &&
  3338. 'adv_network_logo_url' in o.result[0]) {
  3339. o.result = [];
  3340. changed = true;
  3341. }
  3342. if (o.result.show_adv) {
  3343. o.result.show_adv = false;
  3344. changed = true;
  3345. }
  3346. }
  3347. if (changed) {
  3348. _console.log('changed response >>', o);
  3349. res = JSON.stringify(o);
  3350. }
  3351. this.__responseText__ = res;
  3352. return res;
  3353. };
  3354. Object.defineProperty(XMLHttpRequest.prototype, 'responseText', _responseText);
  3355. },
  3356.  
  3357. 'kakprosto.ru': () => scriptLander(() => {
  3358. selectiveCookies('yadb');
  3359. abortExecution.inlineScript('yaProxy', {
  3360. pattern: /yadb/
  3361. });
  3362. abortExecution.inlineScript('yandexContextAsyncCallbacks');
  3363. abortExecution.inlineScript('adfoxAsyncParams');
  3364. abortExecution.inlineScript('adfoxBackGroundLoaded');
  3365. }, selectiveCookies, abortExecution),
  3366.  
  3367. 'kinopoisk.ru': () => {
  3368. // filter cookies
  3369. // set no-branding body style and adjust other blocks on the page
  3370. const style = {
  3371. '.app__header.app__header_margin-bottom_brand, #top': {
  3372. margin_bottom: '20px !important'
  3373. },
  3374. '.app__branding': {
  3375. display: 'none!important'
  3376. }
  3377. };
  3378. if (location.hostname === 'www.kinopoisk.ru' && !location.pathname.startsWith('/games/'))
  3379. style['html:not(#id), body:not(#id), .app-container'] = {
  3380. background: '#d5d5d5 url(/images/noBrandBg.jpg) 50% 0 no-repeat !important'
  3381. };
  3382. createStyle(style);
  3383. scriptLander(() => {
  3384. selectiveCookies('cmtchd|crookie|kpunk');
  3385. // filter JSON
  3386. win.JSON.parse = new Proxy(win.JSON.parse, {
  3387. apply(fun, that, args) {
  3388. let o = _apply(fun, that, args);
  3389. let name = 'antiAdBlockCookieName';
  3390. if (name in o && typeof o[name] === 'string')
  3391. selectiveCookies(o[name]);
  3392. name = 'branding';
  3393. if (name in o) o[name] = {};
  3394. // tricks against ads in the trailer player
  3395. // if (location.hostname.startsWith('widgets.'))
  3396. if (o.page && o.page.playerParams)
  3397. delete o.page.playerParams.adConfig;
  3398. if (o.common && o.common.bunker && o.common.bunker.adv && o.common.bunker.adv.filmIdWithoutAd)
  3399. o.common.bunker.adv.filmIdWithoutAd.includes = () => true;
  3400. //_console.log('JSON.parse', o);
  3401. return o;
  3402. }
  3403. });
  3404. // skip timeout check for blocked requests
  3405. win.setTimeout = new Proxy(win.setTimeout, {
  3406. apply(fun, that, args) {
  3407. if (args[1] === 100) {
  3408. let str = _toString(args[0]);
  3409. if (str.endsWith('{a()}') || str.endsWith('{n()}'))
  3410. return;
  3411. }
  3412. return _apply(fun, that, args);
  3413. }
  3414. });
  3415. // obfuscated Yandex.Direct
  3416. nt.define('Object.prototype.initYaDirect', undefined);
  3417. nt.define('Object.prototype._resolveDetectResult', () => null);
  3418. nt.define('Object.prototype.detectResultPromise', new Promise(r => r(false)));
  3419. if (location.hostname === 'www.kinopoisk.ru')
  3420. nt.define('Object.prototype.initAd', nt.func(undefined, 'initAd'));
  3421. // catch branding and other things
  3422. let _KP;
  3423. Object.defineProperty(win, 'KP', {
  3424. get() {
  3425. return _KP;
  3426. },
  3427. set(val) {
  3428. if (_KP === val)
  3429. return true;
  3430. _KP = new Proxy(val, {
  3431. set(kp, name, val) {
  3432. if (name === 'branding') {
  3433. kp[name] = new Proxy({
  3434. weborama: {}
  3435. }, {
  3436. get(kp, name) {
  3437. return name in kp ? kp[name] : '';
  3438. },
  3439. set() {}
  3440. });
  3441. return true;
  3442. }
  3443. if (name === 'config')
  3444. val = new Proxy(val, {
  3445. set(cfg, name, val) {
  3446. if (name === 'anContextUrl')
  3447. return true;
  3448. if (name === 'adfoxEnabled' || name === 'hasBranding')
  3449. val = false;
  3450. if (name === 'adfoxVideoAdUrls')
  3451. val = {
  3452. flash: {},
  3453. html: {}
  3454. };
  3455. cfg[name] = val;
  3456. return true;
  3457. }
  3458. });
  3459. kp[name] = val;
  3460. return true;
  3461. }
  3462. });
  3463. _console.log('KP =', val);
  3464. }
  3465. });
  3466. }, selectiveCookies, nullTools);
  3467. },
  3468.  
  3469. 'korrespondent.net': {
  3470. now: () => scriptLander(() => {
  3471. nt.define('holder', function (id) {
  3472. let div = _document.getElementById(id);
  3473. if (!div)
  3474. return;
  3475. if (div.parentNode.classList.contains('col__sidebar')) {
  3476. div.parentNode.appendChild(div);
  3477. div.style.height = '300px';
  3478. }
  3479. });
  3480. }, nullTools),
  3481. dom() {
  3482. for (let frame of _document.querySelectorAll('.unit-side-informer > iframe'))
  3483. frame.parentNode.style.width = '1px';
  3484. }
  3485. },
  3486.  
  3487. 'libertycity.ru': () => scriptLander(() => {
  3488. nt.define('adBlockEnabled', false);
  3489. }, nullTools),
  3490.  
  3491. 'liveinternet.ru': () => scriptLander(() => {
  3492. abortExecution.onGet('Object.prototype.initAd');
  3493. }, abortExecution),
  3494.  
  3495. 'livejournal.com': () => scriptLander(() => {
  3496. nt.define('Object.prototype.Adf', undefined);
  3497. nt.define('Object.prototype.Begun', undefined);
  3498. }, nullTools),
  3499.  
  3500. 'mail.ru': {
  3501. other: 'ok.ru, sportmail.ru',
  3502. now: () => scriptLander(() => {
  3503. const _hostparts = location.hostname.split('.');
  3504. const _subdomain = _hostparts.slice(-3).join('.');
  3505. const _hostname = _hostparts.slice(-2).join('.');
  3506. const _emailru = _subdomain === 'e.mail.ru' || _subdomain === 'octavius.mail.ru';
  3507. const _mymailru = _subdomain === 'my.mail.ru';
  3508. const _okru = _hostname === 'ok.ru';
  3509. // setTimeout filter
  3510. // advBlock|rbParams - ads
  3511. // document\.title= - blinking title on background news load on main page
  3512. const pattern = /advBlock|rbParams|document\.title=/i;
  3513. const _setTimeout = win.setTimeout;
  3514. win.setTimeout = function setTimeout(...args) {
  3515. let text = _toString(args[0]);
  3516. if (pattern.test(text)) {
  3517. _console.trace('Skipped setTimeout:', text);
  3518. return;
  3519. }
  3520. return _setTimeout(...args);
  3521. };
  3522.  
  3523. // Trick to prevent mail.ru from removing 3rd-party styles
  3524. nt.define('Object.prototype.restoreVisibility', nt.func(null, 'restoreVisibility'));
  3525. // Other Yandex Direct and other ads
  3526. nt.define('Object.prototype.initMimic', undefined);
  3527. nt.define('Object.prototype.hpConfig', undefined);
  3528. nt.define('Object.prototype.direct', undefined);
  3529. const getAds = () => new Promise(
  3530. r => r(nt.proxy({}, '?.getAds()'))
  3531. );
  3532. nt.define('Object.prototype.getAds', getAds);
  3533. nt.define('rb_counter', nt.func(null, 'rb_counter'));
  3534. if (_subdomain === 'mail.ru') { // main page
  3535. nt.define('Object.prototype.baits', undefined); // detector
  3536. nt.define('Object.prototype.getFeed', nt.func(null, 'pulse.getFeed')); // Pulse feed
  3537. createStyle('body > div > .pulse { display: none !important }');
  3538. }
  3539. if (_emailru)
  3540. nt.define('Object.prototype.show_me_ads', undefined);
  3541. else if (_mymailru)
  3542. nt.define('Object.prototype.runMimic', nt.func(null, 'runMimic'));
  3543. else {
  3544. nt.define('Object.prototype.mimic', undefined);
  3545. const xray = nt.func(undefined, 'xray');
  3546. nt.defineOn(xray, 'send', nt.func(undefined, 'xray.send'), 'xray.');
  3547. nt.defineOn(xray, 'radarPrefix', null, 'xray.');
  3548. nt.defineOn(xray, 'xrayRadarUrl', undefined, 'xray.');
  3549. nt.defineOn(xray, 'defaultParams', nt.proxy({
  3550. i: undefined,
  3551. p: 'media'
  3552. }), 'xray.');
  3553. nt.define('Object.prototype.xray', nt.proxy(xray));
  3554. }
  3555. // shenanigans against ok.ru ABP detector
  3556. if (_okru) {
  3557. abortExecution.onGet('OK.hooks');
  3558. // banners on ok.ru and counter
  3559. nt.define('getAdvTargetParam', nt.func(null, 'getAdvTargetParam'));
  3560. // break detection in case detector wasn't wrapped
  3561. abortExecution.onSet('Object.prototype.adBlockDetected');
  3562. }
  3563. // news.mail.ru and sportmail.ru
  3564. abortExecution.onGet('myWidget');
  3565. // cleanup e.mail.ru configs and mimic config on news and sport
  3566. const emptyString = (root, name) => root[name] && (root[name] = '');
  3567. const detectMimic = /direct|240x400|SlotView/;
  3568. win.JSON.parse = new Proxy(win.JSON.parse, {
  3569. apply(fun, that, args) {
  3570. let o = _apply(fun, that, args);
  3571. if (o && typeof o === 'object') {
  3572. if (o.cfg && o.cfg.sotaFeatures) {
  3573. let root = o.cfg.sotaFeatures;
  3574. if (Array.isArray(root.adv)) root.adv = [];
  3575. for (let name in root)
  3576. if (name.startsWith('adv-') || name.startsWith('adman-'))
  3577. delete root[name];
  3578. ['email_logs_to', 'smokescreen-locators'].forEach(name => emptyString(root, name));
  3579. }
  3580. if (o.userConfig) {
  3581. if (Array.isArray(o.userConfig.honeypot))
  3582. o.userConfig.honeypot.forEach((v, id, me) => (me[id] = []));
  3583. const cfg = o.userConfig.config;
  3584. if (cfg && cfg.honeypot)
  3585. emptyString(cfg.honeypot, 'baits');
  3586. }
  3587. if (o.body) {
  3588. const flags = o.body.common_purpose_flags;
  3589. if (flags && 'hide_ad_in_mail_web' in flags)
  3590. flags.hide_ad_in_mail_web = true;
  3591. if (o.body.show_me_ads)
  3592. o.body.show_me_ads = false;
  3593. }
  3594. //_console.log('JSON.parse', o);
  3595. }
  3596. if (Array.isArray(o))
  3597. if (o.some(t => typeof t === 'string' && detectMimic.test(t))) {
  3598. _console.log('Replaced', o);
  3599. o = [];
  3600. } //else _console.log('JSON.parse', o);
  3601. return o;
  3602. }
  3603. });
  3604. // all the rest is only needed on main page and in emails
  3605. if (_subdomain !== 'mail.ru' && !_emailru && !_okru)
  3606. return;
  3607.  
  3608. // Disable page scrambler on mail.ru to let extensions easily block ads there
  3609. let logger = {
  3610. apply(fun, that, args) {
  3611. let res = _apply(fun, that, args);
  3612. _console.log(`${fun._name}(`, ...args, `)\n>>`, res);
  3613. return res;
  3614. }
  3615. };
  3616.  
  3617. function wrapLocator(locator) {
  3618. if ('setup' in locator) {
  3619. let _setup = locator.setup;
  3620. locator.setup = function (o) {
  3621. if ('enable' in o) {
  3622. o.enable = false;
  3623. _console.log('Disable mimic mode.');
  3624. }
  3625. if ('links' in o) {
  3626. o.links = [];
  3627. _console.log('Call with empty list of sheets.');
  3628. }
  3629. return _setup.call(this, o);
  3630. };
  3631. locator.insertSheet = () => false;
  3632. locator.wrap = () => false;
  3633. }
  3634. try {
  3635. let names = [];
  3636. for (let name in locator)
  3637. if (typeof locator[name] === 'function' && name !== 'transform') {
  3638. locator[name]._name = "locator." + name;
  3639. locator[name] = new Proxy(locator[name], logger);
  3640. names.push(name);
  3641. }
  3642. _console.log(`[locator] wrapped properties: ${names.length ? names.join(', ') : '[empty]'}`);
  3643. } catch (e) {
  3644. _console.log(e);
  3645. }
  3646. return locator;
  3647. }
  3648.  
  3649. function defineLocator(root) {
  3650. let _locator = root.locator;
  3651. let wrapLocatorSetter = vl => _locator = wrapLocator(vl);
  3652. let loc_desc = Object.getOwnPropertyDescriptor(root, 'locator');
  3653. if (!loc_desc || loc_desc.set !== wrapLocatorSetter)
  3654. try {
  3655. Object.defineProperty(root, 'locator', {
  3656. set: wrapLocatorSetter,
  3657. get() {
  3658. return _locator;
  3659. }
  3660. });
  3661. } catch (err) {
  3662. _console.log('Unable to redefine "locator" object!!!', err);
  3663. }
  3664. if (loc_desc.value)
  3665. _locator = wrapLocator(loc_desc.value);
  3666. }
  3667.  
  3668. { // auto-stubs for various ad, detection and obfuscation modules
  3669. const missingCheck = {
  3670. get(obj, name) {
  3671. let res = obj[name];
  3672. if (!(name in obj))
  3673. _console.trace(`Missing "${name}" in`, obj);
  3674. return res;
  3675. }
  3676. };
  3677. const skipLog = (name, ret) => (...args) => (_console.log(`${name}(`, ...args, ')'), ret);
  3678. const createSkipAllObject = (baseName, obj = {
  3679. __esModule: true
  3680. }) => new Proxy(obj, {
  3681. get(obj, name) {
  3682. if (name in obj)
  3683. return obj[name];
  3684. _console.log(`Created stub for "${name}" in ${baseName}.`);
  3685. obj[name] = skipLog(`${baseName}.${name}`);
  3686. return obj[name];
  3687. },
  3688. set() {}
  3689. });
  3690. const redefiner = {
  3691. apply(fun, that, args) {
  3692. let res;
  3693. let warn = false;
  3694. let name = fun._name;
  3695. if (name === 'mrg-smokescreen/Welter')
  3696. res = {
  3697. isWelter() {
  3698. return true;
  3699. },
  3700. wrap: skipLog(`${name}.wrap`)
  3701. };
  3702. if (name === 'mrg-smokescreen/Honeypot')
  3703. res = {
  3704. check(...args) {
  3705. _console.log(`${name}.check(`, ...args, ')');
  3706. return new Promise(() => undefined);
  3707. },
  3708. version: "-1"
  3709. };
  3710. if (name === 'advert/adman/adman') {
  3711. let features = {
  3712. siteZones: {},
  3713. slots: {}
  3714. };
  3715. [
  3716. 'expId', 'siteId', 'mimicEndpoint', 'mimicPartnerId',
  3717. 'immediateFetchTimeout', 'delayedFetchTimeout'
  3718. ].forEach(name => void(features[name] = null));
  3719. res = createSkipAllObject(name, {
  3720. getFeatures: skipLog(`${name}.getFeatures`, features)
  3721. });
  3722. }
  3723. if (name === 'mrg-smokescreen/Utils')
  3724. res = createSkipAllObject(name, {
  3725. extend(...args) {
  3726. let res = {
  3727. enable: false,
  3728. match: [],
  3729. links: []
  3730. };
  3731. _console.log(`${name}.extend(`, ...args, ') >>', res);
  3732. return res;
  3733. }
  3734. });
  3735. if (name.startsWith('OK/banners/') ||
  3736. name.startsWith('mrg-smokescreen/StyleSheets') ||
  3737. name === '@mail/mimic' ||
  3738. name === 'mediator/advert-managers')
  3739. res = createSkipAllObject(name);
  3740. if (res) {
  3741. Object.defineProperty(res, Symbol.toStringTag, {
  3742. get() {
  3743. return `Skiplog object for ${name}`;
  3744. }
  3745. });
  3746. Object.defineProperty(res, Symbol.toPrimitive, {
  3747. value(hint) {
  3748. if (hint === 'string')
  3749. return Object.prototype.toString.call(this);
  3750. return `[missing toPrimitive] ${name} ${hint}`;
  3751. }
  3752. });
  3753. res = new Proxy(res, missingCheck);
  3754. } else {
  3755. res = _apply(fun, that, args);
  3756. warn = true;
  3757. }
  3758. _console[warn ? 'warn' : 'log'](name, '(', ...args, ')\n>>', res);
  3759. return res;
  3760. }
  3761. };
  3762.  
  3763. const advModuleNamesStartWith = /^(mrg-(context|honeypot)|adv\/)/;
  3764. const advModuleNamesGeneric = /advert|banner|mimic|smoke/i;
  3765. const wrapAdFuncs = {
  3766. apply(fun, that, args) {
  3767. let module = args[0];
  3768. if (typeof module === 'string')
  3769. if ((advModuleNamesStartWith.test(module) ||
  3770. advModuleNamesGeneric.test(module)) &&
  3771. // fix for e.mail.ru in Fx56 and below, looks like Proxy is quirky there
  3772. !module.startsWith('patron.v2.')) {
  3773. let main = args[args.length - 1];
  3774. main._name = module;
  3775. args[args.length - 1] = new Proxy(main, redefiner);
  3776. }
  3777. return _apply(fun, that, args);
  3778. }
  3779. };
  3780. const wrapDefine = def => {
  3781. if (!def)
  3782. return;
  3783. _console.log('define =', def);
  3784. def = new Proxy(def, wrapAdFuncs);
  3785. def._name = 'define';
  3786. return def;
  3787. };
  3788. let _define = wrapDefine(win.define);
  3789. Object.defineProperty(win, 'define', {
  3790. get() {
  3791. return _define;
  3792. },
  3793. set(x) {
  3794. if (_define === x)
  3795. return true;
  3796. _define = wrapDefine(x);
  3797. return true;
  3798. }
  3799. });
  3800. }
  3801.  
  3802. let _honeyPot;
  3803.  
  3804. function defineDetector(mr) {
  3805. let __ = mr._ || {};
  3806. let setHoneyPot = o => {
  3807. if (!o || o === _honeyPot) return;
  3808. _console.log('[honeyPot]', o);
  3809. _honeyPot = function () {
  3810. this.check = new Proxy(() => {
  3811. __.STUCK_IN_POT = false;
  3812. return false;
  3813. }, logger);
  3814. this.check._name = 'honeyPot.check';
  3815. this.destroy = () => null;
  3816. };
  3817. };
  3818. if ('honeyPot' in mr)
  3819. setHoneyPot(mr.honeyPot);
  3820. else
  3821. Object.defineProperty(mr, 'honeyPot', {
  3822. get() {
  3823. return _honeyPot;
  3824. },
  3825. set: setHoneyPot
  3826. });
  3827.  
  3828. __ = new Proxy(__, {
  3829. get(target, prop) {
  3830. return target[prop];
  3831. },
  3832. set(target, prop, val) {
  3833. _console.log(`mr._.${prop} =`, val);
  3834. target[prop] = val;
  3835. return true;
  3836. }
  3837. });
  3838. mr._ = __;
  3839. }
  3840.  
  3841. function defineAdd(mr) {
  3842. let _add;
  3843. let addWrapper = {
  3844. apply(fun, that, args) {
  3845. let module = args[0];
  3846. if (typeof module === 'string' && module.startsWith('ad')) {
  3847. _console.log('Skip module:', module);
  3848. return;
  3849. }
  3850. if (typeof module === 'object' && module.name.startsWith('ad'))
  3851. _console.log('Loaded module:', module);
  3852. return logger.apply(fun, that, args);
  3853. }
  3854. };
  3855. let setMrAdd = v => {
  3856. if (!v) return;
  3857. v._name = 'mr.add';
  3858. v = new Proxy(v, addWrapper);
  3859. _add = v;
  3860. };
  3861. if ('add' in mr)
  3862. setMrAdd(mr.add);
  3863. Object.defineProperty(mr, 'add', {
  3864. get() {
  3865. return _add;
  3866. },
  3867. set: setMrAdd
  3868. });
  3869.  
  3870. }
  3871.  
  3872. const _mr_wrapper = vl => {
  3873. defineLocator(vl.mimic ? vl.mimic : vl);
  3874. defineDetector(vl);
  3875. defineAdd(vl);
  3876. return vl;
  3877. };
  3878. if ('mr' in win) {
  3879. _console.log('Found existing "mr" object.');
  3880. win.mr = _mr_wrapper(win.mr);
  3881. } else {
  3882. let _mr;
  3883. Object.defineProperty(win, 'mr', {
  3884. get() {
  3885. return _mr;
  3886. },
  3887. set(vl) {
  3888. _mr = vl ? _mr_wrapper(vl) : vl;
  3889. },
  3890. configurable: true
  3891. });
  3892. let _defineProperty = _bindCall(Object.defineProperty);
  3893. Object.defineProperty = function defineProperty(...args) {
  3894. const [obj, name, conf] = args;
  3895. if (name === 'mr' && obj instanceof Window) {
  3896. _console.trace('Object.defineProperty(', ...args, ')');
  3897. conf.set(_mr_wrapper(conf.get()));
  3898. }
  3899. if ((name === 'honeyPot' || name === 'add') && _mr === obj && conf.set)
  3900. return;
  3901. return _defineProperty(this, ...args);
  3902. };
  3903. }
  3904. }, nullTools, selectiveCookies, abortExecution)
  3905. },
  3906.  
  3907. 'oms.matchat.online': () => scriptLander(() => {
  3908. let _rmpGlobals;
  3909. Object.defineProperty(win, 'rmpGlobals', {
  3910. get() {
  3911. return _rmpGlobals;
  3912. },
  3913. set(val) {
  3914. if (val === _rmpGlobals)
  3915. return true;
  3916. _rmpGlobals = new Proxy(val, {
  3917. get(obj, name) {
  3918. if (name === 'adBlockerDetected')
  3919. return false;
  3920. return obj[name];
  3921. },
  3922. set(obj, name, val) {
  3923. if (name === 'adBlockerDetected')
  3924. _console.trace('rmpGlobals.adBlockerDetected =', val);
  3925. else
  3926. obj[name] = val;
  3927. return true;
  3928. }
  3929. });
  3930. }
  3931. });
  3932. }),
  3933.  
  3934. 'megogo.net': {
  3935. now() {
  3936. nt.define('adBlock', false);
  3937. nt.define('showAdBlockMessage', nt.func(null, 'showAdBlockMessage'));
  3938. }
  3939. },
  3940.  
  3941. 'naruto-base.su': () => gardener('div[id^="entryID"],.block', /href="http.*?target="_blank"/i),
  3942.  
  3943. 'otzovik.com': () => scriptLander(() => {
  3944. abortExecution.onGet('Object.prototype.DirectManagerStart');
  3945. abortExecution.onGet('Object.prototype._visibilityConfirmer');
  3946. let _o_math = win.o_math;
  3947. Object.defineProperty(win, 'o_math', {
  3948. get() {
  3949. return _o_math;
  3950. },
  3951. set(val) {
  3952. delete val.ext_uid;
  3953. _o_math = val;
  3954. }
  3955. });
  3956. }, abortExecution, selectiveCookies),
  3957.  
  3958. 'overclockers.ru': {
  3959. now() {
  3960. abortExecution.onAll('cardinals');
  3961. abortExecution.inlineScript('Document.prototype.createElement', {
  3962. pattern: /mamydirect/
  3963. });
  3964. }
  3965. },
  3966.  
  3967. 'peka2.tv': () => {
  3968. let bodyClass = 'body--branding';
  3969. let checkNode = node => {
  3970. for (let className of node.classList)
  3971. if (className.includes('banner') || className === bodyClass) {
  3972. _removeAttribute(node, 'style');
  3973. node.classList.remove(className);
  3974. for (let attr of Array.from(node.attributes))
  3975. if (attr.name.startsWith('advert'))
  3976. _removeAttribute(node, attr.name);
  3977. }
  3978. };
  3979. (new MutationObserver(ms => {
  3980. let m, node;
  3981. for (m of ms)
  3982. for (node of m.addedNodes)
  3983. if (node instanceof HTMLElement)
  3984. checkNode(node);
  3985. })).observe(_de, {
  3986. childList: true,
  3987. subtree: true
  3988. });
  3989. (new MutationObserver(ms => {
  3990. for (let m of ms)
  3991. checkNode(m.target);
  3992. })).observe(_de, {
  3993. attributes: true,
  3994. subtree: true,
  3995. attributeFilter: ['class']
  3996. });
  3997. },
  3998.  
  3999. 'pikabu.ru': () => gardener('.story', /story__author[^>]+>ads</i, {
  4000. root: '.inner_wrap',
  4001. observe: true
  4002. }),
  4003.  
  4004. 'piratbit.tld': {
  4005. other: 'pb.wtf',
  4006. dom() {
  4007. const remove = node => node && node.parentNode && (_console.log('removed', node), node.parentNode.removeChild(node));
  4008. const isAdLink = el => location.hostname === el.hostname && /^\/(\w{3}|exit|out)\/[\w=/]{20,}$/.test(el.pathname);
  4009. // line above topic content and images in the slider in the header
  4010. for (let el of _document.querySelectorAll('.releas-navbar div a, #page_contents a'))
  4011. if (isAdLink(el))
  4012. remove(el.closest('tr[class]:not(.top_line):not(.active), .row2[id^="post_"]') || el.closest('div[style]:not(.row1):not(.btn-group)'));
  4013. }
  4014. },
  4015.  
  4016. 'pixelexperience.org': () => scriptLander(() => {
  4017. abortExecution.inlineScript('eval', {
  4018. pattern: /blockadblock/
  4019. });
  4020. }, abortExecution),
  4021.  
  4022. 'player.starlight.digital': () => scriptLander(() => {
  4023. let _currVideo = win.currVideo;
  4024. Object.defineProperty(win, 'currVideo', {
  4025. get() {
  4026. return _currVideo;
  4027. },
  4028. set(val) {
  4029. _console.log('currVideo =', val);
  4030. if ('adv' in val)
  4031. val.adv.creatives = [];
  4032. if ('showadv' in val)
  4033. val.showadv = false;
  4034. if ('mediaHls' in val)
  4035. val.mediaHls = val.mediaHls.replace('adv=1', 'adv=0');
  4036. if ('media' in val)
  4037. for (let media of val.media)
  4038. media.url = media.url.replace('adv=1', 'adv=0');
  4039. _currVideo = val;
  4040. }
  4041. });
  4042. }, nullTools),
  4043.  
  4044. 'qrz.ru': {
  4045. now() {
  4046. nt.define('ab', false);
  4047. nt.define('tryMessage', nt.func(null, 'tryMessage'));
  4048. }
  4049. },
  4050.  
  4051. 'rambler.ru': {
  4052. other: [
  4053. 'autorambler.ru', 'championat.com', 'eda.ru', 'gazeta.ru', 'lenta.ru', 'letidor.ru',
  4054. 'media.eagleplatform.com', 'motor.ru', 'passion.ru', 'quto.ru', 'rns.online', 'wmj.ru'
  4055. ].join(','),
  4056. now() {
  4057. scriptLander(() => {
  4058. // skip login form and frames, nothing to do here
  4059. if (location.hostname === 'id.rambler.ru')
  4060. return;
  4061.  
  4062. // prevent autoplay
  4063. if (location.hostname === 'vp.rambler.ru') {
  4064. nt.define('Object.prototype.onVisibleAreaChanged', () => false);
  4065. return;
  4066. }
  4067. if (location.hostname.endsWith('.media.eagleplatform.com')) {
  4068. const _stopImmediatePropagation = _bindCall(Event.prototype.stopImmediatePropagation);
  4069. win.addEventListener('message', e => {
  4070. if (typeof e.data === 'object' && e.data.visible)
  4071. _stopImmediatePropagation(e);
  4072. });
  4073. return;
  4074. }
  4075. /* jshint -W001 */ // aka 'hasOwnProperty' is a really bad name, but this is a wrapper
  4076. const autoList = new Set(['autoplay', 'scrollplay']);
  4077. win.Object.prototype.hasOwnProperty = new Proxy(win.Object.prototype.hasOwnProperty, {
  4078. apply(fun, that, args) {
  4079. if (autoList.has(args[0]))
  4080. return false;
  4081. return _apply(fun, that, args);
  4082. }
  4083. });
  4084. /* jshint +W001 */
  4085.  
  4086. selectiveCookies('detect_count|dv|dvr|lv|lvr');
  4087. // Wrapper for adv loader settings in QW50aS1BZEJsb2Nr['7t7hystz']
  4088. const _contexts = new WeakMap();
  4089. Object.defineProperty(Object.prototype, 'Settings', {
  4090. set(val) {
  4091. if (typeof val === 'object' && 'Transports' in val && 'Urls' in val)
  4092. val.Urls = [];
  4093. _contexts.set(this, val);
  4094. },
  4095. get() {
  4096. return _contexts.get(this);
  4097. }
  4098. });
  4099. // disable video pop-outs in articles on gazeta.ru
  4100. if (location.hostname === 'gazeta.ru' || location.hostname.endsWith('.gazeta.ru'))
  4101. nt.define('creepyVideo', nt.func(null, 'creepyVideo'));
  4102. // disable some logging
  4103. yandexRavenStub();
  4104. // hide "disable ads" button
  4105. createStyle('a[href^="https://prime.rambler.ru/promo/"] { display: none !important }');
  4106. // prevent ads from loading
  4107. abortExecution.onGet('g_GazetaNoExchange');
  4108.  
  4109. //const blockPatterns = /[[:][a-z]{1,4}\("0x[\da-f]+"\)[\],}]|{[a-z]{1,2}\([a-z]{1,2}\)}|\.(rnet\.plus|24smi\.net|infox\.sg|lentainform\.com)\//i;
  4110. const isLocalScript = () => {
  4111. let e = removeOwnFootprint(new Error());
  4112. let parse = /(https?:.*?):\d+:\d+(\n|\51)/.exec(e.stack); // \51 is an octal code of closing round bracket
  4113. return parse && parse[1] === location.href;
  4114. };
  4115. const cutoff = 200;
  4116. win.setTimeout = new Proxy(win.setTimeout, {
  4117. apply(fun, that, args) {
  4118. if (isLocalScript()) {
  4119. const [callback, delay] = args;
  4120. const str = _toString(callback);
  4121. if (!/\n/.test(str)) { //
  4122. _console.trace(`Skipped setTimeout(${str.slice(0, cutoff)}${str.length > cutoff ? '\u2026' : ''}, ${delay})`);
  4123. return null;
  4124. }
  4125. }
  4126. return _apply(fun, that, args);
  4127. }
  4128. });
  4129. const _onerror = Object.getOwnPropertyDescriptor(win.HTMLElement.prototype, 'onerror');
  4130. _onerror.set = new Proxy(_onerror.set, {
  4131. apply(fun, that, args) {
  4132. const [callback] = args;
  4133. if (typeof callback === 'function' && isLocalScript()) {
  4134. const str = _toString(callback);
  4135. _console.trace(`Skipped onerror = ${str.slice(0, cutoff)}${str.length > cutoff ? '\u2026' : ''}`);
  4136. return;
  4137. }
  4138. return _apply(fun, that, args);
  4139. }
  4140. });
  4141. Object.defineProperty(win.HTMLElement.prototype, 'onerror', _onerror);
  4142. // Skip dev console check
  4143. win.console.debug = new Proxy(win.console.debug, {
  4144. apply(fun, that, args) {
  4145. if (args[0] instanceof HTMLImageElement)
  4146. return;
  4147. return _apply(fun, that, args);
  4148. }
  4149. });
  4150. // Defense against triggered detector
  4151. _Node.removeChild = new Proxy(_Node.removeChild, {
  4152. apply(fun, that, args) {
  4153. const [el] = args;
  4154. if (el.tagName === 'LINK' && isLocalScript()) {
  4155. _console.log(`Let's not remove ${el.tagName}.`);
  4156. return;
  4157. }
  4158. return _apply(fun, that, args);
  4159. }
  4160. });
  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://greasyfork.org/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://greasyfork.org/${opts.Lang.slice(0,2)}/scripts/19993-ru-adlist-js-fixes#additional-info`);
  5593. });
  5594. }
  5595. })();