RU AdList JS Fixes

try to take over the world!

当前为 2020-10-18 提交的版本,查看 最新版本

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