RU AdList JS Fixes

try to take over the world!

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

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