RU AdList JS Fixes

try to take over the world!

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

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