RU AdList JS Fixes

try to take over the world!

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

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