RU AdList JS Fixes

try to take over the world!

目前为 2020-10-15 提交的版本,查看 最新版本

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