RU AdList JS Fixes

try to take over the world!

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

  1. // ==UserScript==
  2. // @name RU AdList JS Fixes
  3. // @namespace ruadlist_js_fixes
  4. // @version 20201101.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 && parseInt((navigator.userAgent.match(/Firefox\/(\d+)\./) || [])[1]) <= 60) {
  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. function documentRewrite(pattern, substitute) {
  2435. /* jshint -W060 */ // document.write is a form of evil, a necessary evil in this case
  2436. const inject = (pattern, substitute) => {
  2437. let xhr = new XMLHttpRequest();
  2438. xhr.open('GET', location.href);
  2439. xhr.onload = () => {
  2440. document.close();
  2441. document.write(xhr.responseText.replace(pattern, substitute));
  2442. document.close();
  2443. };
  2444. xhr.send();
  2445. };
  2446. /* jshint +W060 */
  2447. const style = [
  2448. '@keyframes spinner { 0% { transform: translate3d(-50%, -50%, 0) rotate(0deg); } 100% { transform: translate3d(-50%, -50%, 0) rotate(360deg); } }',
  2449. '.spinner::before { animation: 1.5s linear infinite spinner; animation-play-state: running;',
  2450. 'content: ""; border: solid 3px #dedede; border-bottom-color: #EF6565; border-radius: 50%;',
  2451. 'height: 10vh; width: 10vh; left: 50%; top: 50%; position: absolute; transform: translate3d(-50%, -50%, 0); };'
  2452. ].join('');
  2453. _document.write(`<html><head><script>(${inject.toString()})(${pattern.toString()},'${substitute}')</script>`);
  2454. _document.write(`<style>${style}</style></head><body><div class="spinner"></div></body></html>`);
  2455. }
  2456.  
  2457. // === Scripts for specific domains ===
  2458.  
  2459. const scripts = {
  2460. // prevent popups and redirects block
  2461. // Popups
  2462. preventPopups: {
  2463. other: 'biqle.ru, chaturbate.com, dfiles.ru, eporner.eu, hentaiz.org, mirrorcreator.com, online-multy.ru' +
  2464. 'radikal.ru, rumedia.ws, tapehub.tech, thepiratebay.org, unionpeer.com, zippyshare.com',
  2465. now: preventPopups
  2466. },
  2467. // Popunders (background redirect)
  2468. preventPopunders: {
  2469. other: 'lostfilm-online.ru, mediafire.com, megapeer.org, megapeer.ru, perfectgirls.net',
  2470. now: preventPopunders
  2471. },
  2472. // zmctrack remover
  2473. zmcDocumentRewriteS: {
  2474. other: '112.ua,avtovod.com.ua,besplatka.ua,bigmir.net,buhgalter.com.ua,businessua.com,dengi.ua,ditey.com' +
  2475. ',enovosty.com,epravda.com.ua,eurointegration.com.ua,f1analytic.com,facenews.ua,football-ukraine.com' +
  2476. ',footballgazeta.com,footballtransfer.com.ua,gorod.dp.ua,hvylya.net,inforesist.org,isport.ua' +
  2477. ',kolobok.ua,kp.ua,kriminal.tv,lifedon.com.ua,mport.ua,nashamama.com,nnovosti.info,ostro.org' +
  2478. ',pravda.com.ua,real-vin.com,smak.ua,strana.ua,stravy.net,tv.ua,ukr.net,vsetv.com,zdorovia.com.ua',
  2479. now: () => {
  2480. documentRewrite(/<iframe\sname="n\d+(_\d+)?"\sstyle="display:none"><\/iframe><script>.*?<\/script>/, '<!-- removed -->');
  2481. }
  2482. },
  2483. zmcDocumentRewriteM: {
  2484. other: 'liga.net,segodnya.ua',
  2485. now: () => {
  2486. documentRewrite(/<iframe\sname="n\d+(_\d+)?"\sstyle="display:none"><\/iframe>[\r\n\s]*<script>[\s\S]*?<\/script>/m, '<!-- removed -->');
  2487. }
  2488. },
  2489. zmcPlug: {
  2490. other: '4mama.ua,censor.net,eknigi.org,forumodua.com,internetua.com,newsyou.info,okino.ua,sinoptik.ua' +
  2491. ',toneto.net,tvgid.ua,udoktora.net',
  2492. now: () => {
  2493. if (GM_info.scriptHandler === 'Violentmonkey')
  2494. documentRewrite(/ /, ' ');
  2495. zmcPlug();
  2496. }
  2497. },
  2498. // custom zmc-related fixes
  2499. 'i.ua': () => {
  2500. documentRewrite(/<script type="application\/javascript">\(function\(\) {var _0x.*?}\)\(\)<\/script>/, '<!-- removed -->');
  2501. },
  2502. 'kzblow.info': () => {
  2503. documentRewrite(/<script>\(function\(\w\w,.*?'n\d+'\);<\/script>/, '<!-- removed -->');
  2504. },
  2505.  
  2506. // PopMix (both types of popups encountered on site)
  2507. 'openload.co': {
  2508. other: 'oload.tv, oload.info, openload.co.com',
  2509. now() {
  2510. if (inIFrame) {
  2511. nt.define('BetterJsPop', {
  2512. add(a, b) {
  2513. _console.trace('BetterJsPop.add(%o, %o)', a, b);
  2514. },
  2515. config(o) {
  2516. _console.trace('BetterJsPop.config(%o)', o);
  2517. },
  2518. Browser: {
  2519. isChrome: true
  2520. }
  2521. });
  2522. nt.define('isSandboxed', nt.func(null, 'isSandboxed'));
  2523. nt.define('adblock', false);
  2524. nt.define('adblock2', false);
  2525. } else preventPopMix();
  2526. }
  2527. },
  2528.  
  2529. 'turbobit.net': preventPopMix,
  2530.  
  2531. 'tapochek.net': () => {
  2532. // workaround for moradu.com/apu.php load error handler script, not sure which ad network is this
  2533. let _appendChild = Object.getOwnPropertyDescriptor(_Node, 'appendChild');
  2534. let _appendChild_value = _appendChild.value;
  2535. _appendChild.value = function appendChild(node) {
  2536. if (this === _document.body)
  2537. if ((node instanceof HTMLScriptElement || node instanceof HTMLStyleElement) &&
  2538. /^https?:\/\/[0-9a-f]{15}\.com\/\d+(\/|\.css)$/.test(node.src) ||
  2539. node instanceof HTMLDivElement && node.style.zIndex > 900000 &&
  2540. node.style.backgroundImage.includes('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'))
  2541. throw '...eenope!';
  2542. return _appendChild_value.apply(this, arguments);
  2543. };
  2544. Object.defineProperty(_Node, 'appendChild', _appendChild);
  2545.  
  2546. // disable window focus tricks and changing location
  2547. let focusHandlerName = /\WfocusAchieved\(/;
  2548. let _setInterval = win.setInterval;
  2549. win.setInterval = (...args) => {
  2550. if (args.length && focusHandlerName.test(_toString(args[0]))) {
  2551. _console.log('skip setInterval for', ...args);
  2552. return -1;
  2553. }
  2554. return _setInterval(...args);
  2555. };
  2556. let _addEventListener = win.addEventListener;
  2557. win.addEventListener = function (...args) {
  2558. if (args.length && args[0] === 'focus' && focusHandlerName.test(_toString(args[1]))) {
  2559. _console.log('skip addEventListener for', ...args);
  2560. return undefined;
  2561. }
  2562. return _addEventListener.apply(this, args);
  2563. };
  2564.  
  2565. // generic popup prevention
  2566. preventPopups();
  2567. },
  2568.  
  2569. // = other ======================================================================================
  2570.  
  2571. '1tv.ru': {
  2572. other: 'mediavitrina.ru',
  2573. now: () => scriptLander(() => {
  2574. nt.define('EUMPAntiblockConfig', nt.proxy({
  2575. url: '//www.1tv.ru/favicon.ico'
  2576. }));
  2577. nt.define('Object.prototype.disableSeek', nt.func(undefined, 'disableSeek'));
  2578. //nt.define('preroll', undefined);
  2579.  
  2580. let _EUMP;
  2581. const _EUMP_set = x => {
  2582. if (x === _EUMP)
  2583. return true;
  2584. let _plugins = x.plugins;
  2585. Object.defineProperty(x, 'plugins', {
  2586. enumerable: true,
  2587. get() {
  2588. return _plugins;
  2589. },
  2590. set(vl) {
  2591. if (vl === _plugins)
  2592. return true;
  2593. nt.defineOn(vl, 'antiblock', function (player, opts) {
  2594. const antiblock = nt.proxy({
  2595. opts: opts,
  2596. readyState: 'ready',
  2597. isEUMPPlugin: true,
  2598. detected: nt.func(false, 'antiblock.detected'),
  2599. currentWeight: nt.func(0, 'antiblock.currentWeight')
  2600. });
  2601. player.antiblock = antiblock;
  2602. return antiblock;
  2603. }, 'EUMP.plugins.');
  2604. _plugins = vl;
  2605. }
  2606. });
  2607. _EUMP = x;
  2608. return true;
  2609. };
  2610. if ('EUMP' in win)
  2611. _EUMP_set(win.EUMP);
  2612. Object.defineProperty(win, 'EUMP', {
  2613. enumerable: true,
  2614. get() {
  2615. return _EUMP;
  2616. },
  2617. set: _EUMP_set
  2618. });
  2619.  
  2620. let _EUMPVGTRK;
  2621. const _EUMPVGTRK_set = x => {
  2622. if (x === _EUMPVGTRK)
  2623. return true;
  2624. if (x && x.prototype) {
  2625. if ('generatePrerollUrls' in x.prototype)
  2626. nt.defineOn(x.prototype, 'generatePrerollUrls', nt.func(null, 'EUMPVGTRK.generatePrerollUrls'), 'EUMPVGTRK.prototype.', {
  2627. enumerable: false
  2628. });
  2629. if ('sendAdsEvent' in x.prototype)
  2630. nt.defineOn(x.prototype, 'sendAdsEvent', nt.func(null, 'EUMPVGTRK.sendAdsEvent'), 'EUMPVGTRK.prototype.', {
  2631. enumerable: false
  2632. });
  2633. }
  2634. _EUMPVGTRK = x;
  2635. return true;
  2636. };
  2637. if ('EUMPVGTRK' in win)
  2638. _EUMPVGTRK_set(win.EUMPVGTRK);
  2639. Object.defineProperty(win, 'EUMPVGTRK', {
  2640. enumerable: true,
  2641. get() {
  2642. return _EUMPVGTRK;
  2643. },
  2644. set: _EUMPVGTRK_set
  2645. });
  2646. }, nullTools)
  2647. },
  2648.  
  2649. '24smi.org': () => scriptLander(() => selectiveCookies('has_adblock'), selectiveCookies),
  2650.  
  2651. '2picsun.ru': {
  2652. other: 'pics2sun.ru, 3pics-img.ru',
  2653. now() {
  2654. Object.defineProperty(navigator, 'userAgent', {
  2655. value: 'googlebot'
  2656. });
  2657. }
  2658. },
  2659.  
  2660. '4pda.ru': {
  2661. now() {
  2662. // https://greasyfork.org/en/scripts/14470-4pda-unbrender
  2663. const isForum = location.pathname.startsWith('/forum/'),
  2664. remove = node => (node && node.parentNode.removeChild(node)),
  2665. hide = node => (node && (node.style.display = 'none'));
  2666.  
  2667. selectiveCookies('viewpref');
  2668. abortExecution.inlineScript('document.querySelector', {
  2669. pattern: /\(document(,window)?\);/
  2670. });
  2671.  
  2672. function cleaner(log) {
  2673. HeaderAds: {
  2674. // hide ads above HEADER
  2675. let nav = _document.querySelector('.menu-main-item');
  2676. while (nav && (nav.parentNode !== _de))
  2677. if (!nav.parentNode.querySelector('article, .container[itemtype$="Article"]'))
  2678. nav = nav.parentNode;
  2679. else break;
  2680. if (!nav || (nav.parentNode === _de)) {
  2681. if (log) _console.warn('Unable to locate header element');
  2682. break HeaderAds;
  2683. }
  2684. if (log) _console.log('Processing header:', nav);
  2685. for (let itm of nav.parentNode.children)
  2686. if (itm !== nav)
  2687. hide(itm);
  2688. else break;
  2689. }
  2690.  
  2691. FixNavMenu: {
  2692. // hide ad link from the navigation
  2693. let ad = _document.querySelector('.menu-main-item > a > svg');
  2694. if (!ad) {
  2695. if (log) _console.warn('Unable to locate menu ad item');
  2696. break FixNavMenu;
  2697. } else {
  2698. ad = ad.parentNode.parentNode;
  2699. hide(ad);
  2700. }
  2701. }
  2702.  
  2703. SidebarAds: {
  2704. // remove ads from sidebar
  2705. let aside = _document.querySelectorAll('[class]:not([id]) > [id]:not([class]) > :first-child + :last-child:not(.v-panel)');
  2706. if (!aside.length) {
  2707. if (log) _console.warn('Unable to locate sidebar');
  2708. break SidebarAds;
  2709. }
  2710. let post;
  2711. for (let side of aside) {
  2712. if (log) _console.log('Processing potential sidebar:', side);
  2713. for (let itm of Array.from(side.children)) {
  2714. post = itm.classList.contains('post');
  2715. if (post) continue;
  2716. if (itm.querySelector('iframe') || !itm.children.length)
  2717. remove(itm);
  2718. let script = itm.querySelector('script');
  2719. if (itm.querySelector('a[target="_blank"] > img') ||
  2720. script && script.src === '' && (script.type === 'text/javascript' || !script.type) &&
  2721. script.textContent.includes('document'))
  2722. hide(itm);
  2723. }
  2724. }
  2725. }
  2726. }
  2727.  
  2728. const cln = setInterval(() => cleaner(false), 50);
  2729.  
  2730. // hide banner next to logo
  2731. if (isForum)
  2732. createStyle('div[class]:not([id]) tr[valign="top"] > td:last-child { display: none !important }');
  2733. // clean page
  2734. window.addEventListener(
  2735. 'DOMContentLoaded',
  2736. function () {
  2737. clearInterval(cln);
  2738. const width = () => win.innerWidth || _de.clientWidth || _document.body.clientWidth || 0,
  2739. height = () => win.innerHeight || _de.clientHeight || _document.body.clientHeight || 0;
  2740.  
  2741. if (isForum) {
  2742. // hide banner next to logo
  2743. //let itm = _document.querySelector('#logostrip');
  2744. //if (itm) hide(itm.parentNode.nextSibling);
  2745. // clear background in the download frame
  2746. if (location.pathname.startsWith('/forum/dl/')) {
  2747. let setBackground = node => _setAttribute(
  2748. node,
  2749. 'style', (_getAttribute(node, 'style') || '') +
  2750. ';background-color:#4ebaf6!important'
  2751. );
  2752. setBackground(_document.body);
  2753. for (let itm of _document.querySelectorAll('body > div'))
  2754. if (!itm.querySelector('.dw-fdwlink, .content') && !itm.classList.contains('footer'))
  2755. remove(itm);
  2756. else
  2757. setBackground(itm);
  2758. }
  2759. // exist from DOMContentLoaded since the rest is not for forum
  2760. return;
  2761. }
  2762.  
  2763. cleaner(false);
  2764.  
  2765. _document.body.setAttribute('style', (_document.body.getAttribute('style') || '') + ';background-color:#E6E7E9!important');
  2766.  
  2767. let extra = 'background-image:none!important;background-color:transparent!important',
  2768. fakeStyles = new WeakMap(),
  2769. styleProxy = {
  2770. get(target, prop) {
  2771. return fakeStyles.get(target)[prop] || target[prop];
  2772. },
  2773. set(target, prop, value) {
  2774. let fakeStyle = fakeStyles.get(target);
  2775. ((prop in fakeStyle) ? fakeStyle : target)[prop] = value;
  2776. return true;
  2777. }
  2778. };
  2779. for (let itm of _document.querySelectorAll('[id]:not(A), A')) {
  2780. if (!(itm.offsetWidth > 0.95 * width() &&
  2781. itm.offsetHeight > 0.85 * height()))
  2782. continue;
  2783. if (itm.tagName !== 'A') {
  2784. fakeStyles.set(itm.style, {
  2785. 'backgroundImage': itm.style.backgroundImage,
  2786. 'backgroundColor': itm.style.backgroundColor
  2787. });
  2788.  
  2789. try {
  2790. Object.defineProperty(itm, 'style', {
  2791. value: new Proxy(itm.style, styleProxy),
  2792. enumerable: true
  2793. });
  2794. } catch (e) {
  2795. _console.log('Unable to protect style property.', e);
  2796. }
  2797.  
  2798. _setAttribute(itm, 'style', `${(_getAttribute(itm, 'style') || '')};${extra}`);
  2799. }
  2800. if (itm.tagName === 'A')
  2801. _setAttribute(itm, 'style', 'display:none!important');
  2802. }
  2803. }
  2804. );
  2805. }
  2806. },
  2807.  
  2808. 'adhands.ru': () => scriptLander(() => {
  2809. try {
  2810. let _adv;
  2811. Object.defineProperty(win, 'adv', {
  2812. get() {
  2813. return _adv;
  2814. },
  2815. set(val) {
  2816. _console.log('Blocked advert on adhands.ru.');
  2817. nt.defineOn(val, 'advert', '', 'adv.');
  2818. _adv = val;
  2819. }
  2820. });
  2821. } catch (ignore) {
  2822. if (!win.adv)
  2823. _console.log('Unable to locate advert on adhands.ru.');
  2824. else {
  2825. _console.log('Blocked advert on adhands.ru.');
  2826. nt.define('adv.advert', '');
  2827. }
  2828. }
  2829. }, nullTools),
  2830.  
  2831. 'all-episodes.org': () => {
  2832. nt.define('perROS', 0); // blocks access when = 1
  2833. nt.define('idm', -1); // blocks quality when >= 0
  2834. nt.define('advtss', nt.proxy({
  2835. offsetHeight: 200,
  2836. offsetWidth: 200
  2837. }, 'advtss'));
  2838. // wrap player to prevent some events and interactions
  2839. let _playerInstance = win.playerInstance;
  2840. Object.defineProperty(win, 'playerInstance', {
  2841. get() {
  2842. return _playerInstance;
  2843. },
  2844. set(vl) {
  2845. _console.log('player =', vl, vl.on, vl.getAdBlock);
  2846. vl.on = new Proxy(vl.on, {
  2847. apply(fun, that, args) {
  2848. if (/^(ad[A-Z]|before(Play|Complete))/.test(args[0]))
  2849. return;
  2850. //_console.log('on', ...args);
  2851. return _apply(fun, that, args);
  2852. }
  2853. });
  2854. nt.defineOn(vl, 'getAdBlock', nt.func(false, 'playerInstance.getAdBlock'), 'playerInstance.getAdBlock');
  2855. _playerInstance = vl;
  2856. }
  2857. });
  2858. },
  2859.  
  2860. 'allhentai.ru': () => {
  2861. preventPopups();
  2862. scriptLander(() => {
  2863. selectiveEval();
  2864. let _onerror = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onerror');
  2865. if (!_onerror)
  2866. return;
  2867. _onerror.set = (...args) => _console.log(args[0].toString());
  2868. Object.defineProperty(HTMLElement.prototype, 'onerror', _onerror);
  2869. }, selectiveEval);
  2870. },
  2871.  
  2872. 'allmovie.pro': {
  2873. other: 'rufilmtv.org',
  2874. dom() {
  2875. // pretend to be Android to make site use different played for ads
  2876. if (isSafari)
  2877. return;
  2878. Object.defineProperty(navigator, 'userAgent', {
  2879. get() {
  2880. 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';
  2881. },
  2882. enumerable: true
  2883. });
  2884. }
  2885. },
  2886.  
  2887. 'ati.su': () => scriptLander(() => {
  2888. nt.define('Object.prototype.advManager', nt.proxy({}, 'advManager'));
  2889. }),
  2890.  
  2891. 'audioportal.su': {
  2892. now() {
  2893. createStyle('#blink2 { display: none !important }');
  2894. },
  2895. dom() {
  2896. let links = _document.querySelectorAll('a[onclick*="clickme("]');
  2897. if (!links) return;
  2898. for (let link of links)
  2899. win.clickme(link);
  2900. }
  2901. },
  2902.  
  2903. 'auto.ru': () => {
  2904. let words = /Реклама|Яндекс.Директ|yandex_ad_/;
  2905. let userAdsListAds = (
  2906. '.listing-list > .listing-item,' +
  2907. '.listing-item_type_fixed.listing-item'
  2908. );
  2909. let catalogAds = (
  2910. 'div[class*="layout_catalog-inline"],' +
  2911. 'div[class$="layout_horizontal"]'
  2912. );
  2913. let otherAds = (
  2914. '.advt_auto,' +
  2915. '.sidebar-block,' +
  2916. '.pager-listing + div[class],' +
  2917. '.card > div[class][style],' +
  2918. '.sidebar > div[class],' +
  2919. '.main-page__section + div[class],' +
  2920. '.listing > tbody'
  2921. );
  2922. gardener(userAdsListAds, words, {
  2923. root: '.listing-wrap',
  2924. observe: true
  2925. });
  2926. gardener(catalogAds, words, {
  2927. root: '.catalog__page,.content__wrapper',
  2928. observe: true
  2929. });
  2930. gardener(otherAds, words);
  2931. nt.define('Object.prototype.yaads', undefined);
  2932. nt.define('Object.prototype.initYaDirect', undefined);
  2933. nt.define('Object.prototype.direct', nt.proxy({}, 'Yandex.direct'));
  2934. },
  2935.  
  2936. 'avito.ru': () => scriptLander(() => selectiveCookies('abp|cmtchd|crookie|is_adblock'), selectiveCookies),
  2937.  
  2938. 'di.fm': () => scriptLander(() => {
  2939. let log = false;
  2940. // wrap global app object to catch registration of specific modules
  2941. let _di = win.di;
  2942. Object.defineProperty(win, 'di', {
  2943. get() {
  2944. return _di;
  2945. },
  2946. set(vl) {
  2947. if (vl === _di)
  2948. return;
  2949. if (log) _console.trace('di =', vl);
  2950. _di = new Proxy(vl, {
  2951. set(di, name, vl) {
  2952. if (vl === di[name])
  2953. return true;
  2954. if (name === 'app') {
  2955. if (log) _console.trace(`di.${name} =`, vl);
  2956. if (!('module' in vl))
  2957. return;
  2958. vl.module = new Proxy(vl.module, {
  2959. apply(module, that, args) {
  2960. if (/Wall|Banner|Detect|WebplayerApp\.Ads/.test(args[0])) {
  2961. let name = args[0];
  2962. if (log) _console.log('wrap', name, 'module');
  2963. if (typeof args[1] === 'function')
  2964. args[1] = new Proxy(args[1], {
  2965. apply(fun, that, args) {
  2966. if (args[0]) // module object
  2967. args[0].start = () => _console.log('Skipped start of', name);
  2968. return Reflect.apply(fun, that, args);
  2969. }
  2970. });
  2971. } // else log && _console.log('loading module', args[0]);
  2972. if (args[0] === 'Modals' && typeof args[1] === 'function') {
  2973. if (log) _console.log('wrap', name, 'module');
  2974. args[1] = new Proxy(args[1], {
  2975. apply(fun, that, args) {
  2976. if ('commands' in args[1] && 'setHandlers' in args[1].commands &&
  2977. !Object.hasOwnProperty.call(args[1].commands, 'setHandlers')) {
  2978. let _commands = args[1].commands;
  2979. _commands.setHandlers = new Proxy(_commands.setHandlers, {
  2980. apply(fun, that, args) {
  2981. const noopFunc = name => () => _console.log('Skipped', name, 'window');
  2982. for (let name in args[0])
  2983. if (name === 'modal:streaminterrupt' ||
  2984. name === 'modal:midroll')
  2985. args[0][name] = noopFunc(name);
  2986. delete _commands.setHandlers;
  2987. return Reflect.apply(fun, that, args);
  2988. }
  2989. });
  2990. }
  2991. return Reflect.apply(fun, that, args);
  2992. }
  2993. });
  2994. }
  2995. return Reflect.apply(module, that, args);
  2996. }
  2997. });
  2998. }
  2999. di[name] = vl;
  3000. }
  3001. });
  3002. }
  3003. });
  3004. // don't send errorception logs
  3005. Object.defineProperty(win, 'onerror', {
  3006. set(vl) {
  3007. if (log) _console.trace('Skipped global onerror callback:', vl);
  3008. }
  3009. });
  3010. }),
  3011.  
  3012. 'draug.ru': {
  3013. other: 'vargr.ru',
  3014. now: () => scriptLander(() => {
  3015. if (location.pathname === '/pop.html')
  3016. win.close();
  3017. createStyle({
  3018. '#timer_1': {
  3019. display: 'none !important'
  3020. },
  3021. '#timer_2': {
  3022. display: 'block !important'
  3023. }
  3024. });
  3025. let _contentWindow = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, 'contentWindow');
  3026. let _get_contentWindow = _bindCall(_contentWindow.get);
  3027. _contentWindow.get = function () {
  3028. let res = _get_contentWindow(this);
  3029. if (res.location.href === 'about:blank')
  3030. res.document.write = (...args) => _console.log('Skipped iframe.write(', ...args, ')');
  3031. return res;
  3032. };
  3033. Object.defineProperty(HTMLIFrameElement.prototype, 'contentWindow', _contentWindow);
  3034. }),
  3035. dom() {
  3036. let list = _querySelectorAll('div[id^="yandex_rtb_"], .adsbygoogle');
  3037. list.forEach(node => _console.log('Removed:', node.parentNode.parentNode.removeChild(node.parentNode)));
  3038. }
  3039. },
  3040.  
  3041. 'drive2.ru': () => {
  3042. gardener('.c-block:not([data-metrika="recomm"]),.o-grid__item', />Реклама<\//i);
  3043. scriptLander(() => {
  3044. selectiveCookies();
  3045. let _d2;
  3046. Object.defineProperty(win, 'd2', {
  3047. get() {
  3048. return _d2;
  3049. },
  3050. set(vl) {
  3051. if (vl === _d2)
  3052. return true;
  3053. _d2 = new Proxy(vl, {
  3054. set(target, prop, val) {
  3055. if (['brandingRender', 'dvReveal', '__dv'].includes(prop))
  3056. val = () => null;
  3057. target[prop] = val;
  3058. return true;
  3059. }
  3060. });
  3061. }
  3062. });
  3063. // obfuscated Yandex.Direct
  3064. nt.define('Object.prototype.initYaDirect', undefined);
  3065. }, nullTools, selectiveCookies);
  3066. },
  3067.  
  3068. 'echo.msk.ru': () => scriptLander(() => {
  3069. selectiveCookies();
  3070. selectiveEval(evalPatternYandex, /^document\.write/, /callAdblock/);
  3071. }, selectiveEval, selectiveCookies),
  3072.  
  3073. 'eurogamer.tld': {
  3074. other: 'metabomb.net, usgamer.net',
  3075. now: () => scriptLander(() => {
  3076. abortExecution.inlineScript('_sp_');
  3077. selectiveCookies('sp');
  3078. }, selectiveCookies, abortExecution)
  3079. },
  3080.  
  3081. 'fastpic.ru': () => {
  3082. // Had to obfuscate property name to avoid triggering anti-obfuscation on greasyfork.org -_- (Exception 403012)
  3083. nt.define(`_0x${'4955'}`, []);
  3084. },
  3085.  
  3086. 'fishki.net': () => {
  3087. scriptLander(() => {
  3088. const fishki = {};
  3089. const adv = nt.proxy({
  3090. afterAdblockCheck: nt.func(null, 'fishki.afterAdblockCheck'),
  3091. refreshFloat: nt.func(null, 'fishki.refreshFloat')
  3092. });
  3093. nt.defineOn(fishki, 'adv', adv, 'fishki.');
  3094. nt.defineOn(fishki, 'is_adblock', false, 'fishki.');
  3095. nt.define('fishki', fishki);
  3096. nt.define('Object.prototype.detect', nt.func(undefined, 'detect'));
  3097. win.Object.defineProperty = new Proxy(win.Object.defineProperty, {
  3098. apply(fun, that, args) {
  3099. if (['is_adblock', 'adv'].includes(args[1]) || args[0] === adv)
  3100. return;
  3101. return _apply(fun, that, args);
  3102. }
  3103. });
  3104. }, nullTools);
  3105. gardener('.drag_list > .drag_element, .list-view > .paddingtop15, .post-wrap', /543769|Новости\sпартнеров|Полезная\sреклама/);
  3106. },
  3107.  
  3108. 'forbes.com': () => {
  3109. createStyle(['fbs-ad[ad-id], .top-ad-container, .fbs-ad-wrapper, .footer-ad-labeling, .ad-rail, .ad-unit { display: none !important; }']);
  3110. nt.define('Object.prototype.isAdLight', true);
  3111. nt.define('Object.prototype.initializeAd', nt.func(undefined, '?.initializeAd'));
  3112. win.getComputedStyle = new Proxy(win.getComputedStyle, {
  3113. apply(fun, that, args) {
  3114. let res = _apply(fun, that, args);
  3115. if (res.display === 'none')
  3116. nt.defineOn(res, 'display', 'block', 'getComputedStyle().');
  3117. if (res.visibility === 'hidden')
  3118. nt.defineOn(res, 'visibility', 'visible', 'getComputedStyle().');
  3119. return res;
  3120. }
  3121. });
  3122. win.CSSStyleDeclaration.prototype.getPropertyValue = new Proxy(win.CSSStyleDeclaration.prototype.getPropertyValue, {
  3123. apply(fun, that, args) {
  3124. let res = _apply(fun, that, args);
  3125. if (args[0] === 'display' && res === 'none')
  3126. return 'block';
  3127. if (args[0] === 'visibility' && res === 'hidden')
  3128. return 'visible';
  3129. return res;
  3130. }
  3131. });
  3132. },
  3133.  
  3134. 'friends.in.ua': () => scriptLander(() => {
  3135. Object.defineProperty(win, 'need_warning', {
  3136. get() {
  3137. return 0;
  3138. },
  3139. set() {}
  3140. });
  3141. }),
  3142.  
  3143. 'gamerevolution.com': () => {
  3144. const _clientHeight = Object.getOwnPropertyDescriptor(_Element, 'clientHeight');
  3145. _clientHeight.get = new Proxy(_clientHeight.get, {
  3146. apply(...args) {
  3147. return _apply(...args) || 1;
  3148. }
  3149. });
  3150. Object.defineProperty(_Element, 'clientHeight', _clientHeight);
  3151.  
  3152. const toReplace = [
  3153. 'blockerDetected', 'disableDetected', 'hasAdBlocker',
  3154. 'hasBlockerFlag', 'hasDisabledAdBlocker', 'hasBlocker'
  3155. ];
  3156. win.Object.defineProperty = new Proxy(win.Object.defineProperty, {
  3157. apply(fun, that, args) {
  3158. if (toReplace.includes(args[1])) {
  3159. args[2] = {
  3160. value() {
  3161. return false;
  3162. }
  3163. };
  3164. console.log(args);
  3165. }
  3166. return _apply(fun, that, args);
  3167. }
  3168. });
  3169. },
  3170.  
  3171. 'gamersheroes.com': () => abortExecution.inlineScript('document.createElement', {
  3172. pattern: /window\[\w+\(\[(\d+,?\s?)+\],\s?\w+\)\]/
  3173. }),
  3174.  
  3175. 'gidonline.club': () => createStyle('.tray > div[style] {display: none!important}'),
  3176.  
  3177. 'glav.su': () => scriptLander(() => {
  3178. abortExecution.onSet('abd');
  3179. abortExecution.onSet('script1');
  3180. }, abortExecution),
  3181.  
  3182. 'gorodrabot.ru': () => scriptLander(() => {
  3183. abortExecution.onGet('Object.prototype.yaads');
  3184. abortExecution.onGet('Object.prototype.initYaDirect');
  3185. }, abortExecution),
  3186.  
  3187. 'hdgo.cc': {
  3188. other: '46.30.43.38, couber.be',
  3189. now() {
  3190. (new MutationObserver(
  3191. ms => {
  3192. let m, node;
  3193. for (m of ms)
  3194. for (node of m.addedNodes)
  3195. if (node.tagName instanceof HTMLScriptElement && _getAttribute(node, 'onerror') !== null)
  3196. node.removeAttribute('onerror');
  3197. }
  3198. )).observe(_document.documentElement, {
  3199. childList: true,
  3200. subtree: true
  3201. });
  3202. }
  3203. },
  3204.  
  3205. 'gamepur.com': () => {
  3206. nt.define('ga', nt.func(null, 'ga'));
  3207. win.Object.defineProperty = new Proxy(win.Object.defineProperty, {
  3208. apply(fun, that, args) {
  3209. if (typeof args[1] === 'string' &&
  3210. (args[1] === 'hasAdblocker' || args[1] === 'blockerDetected'))
  3211. throw new TypeError(`Cannot read property '${args[1]}' of undefined`);
  3212. return Reflect.apply(fun, that, args);
  3213. }
  3214. });
  3215. },
  3216.  
  3217. 'gismeteo.tld': {
  3218. now: () => scriptLander(() => {
  3219. /* // rewrite code in case they completely randomize zmc frame name
  3220. documentRewrite(/End\sAfter\scontent[\s\S]*<\/script>/m, '-->');
  3221. */
  3222. zmcPlug();
  3223. // gismeteo dynamically changes name of clean IFrame for zmc every 10 minutes
  3224. // this code attempts to predict this name and block access to it
  3225. const pad = n => n.toString().padStart(2, '0');
  3226. let d = new Date(),
  3227. mon = pad(d.getUTCMonth() + 1),
  3228. day = pad(d.getUTCDate()),
  3229. h24 = pad(d.getUTCHours()),
  3230. m10 = pad(Math.floor(d.getUTCMinutes() / 10) * 10);
  3231. nt.define(`n${mon}${day}${h24}${m10}_11495`, null);
  3232. // hide remaining empty blocks
  3233. gardener('div > script', /AdvManager/i, {
  3234. observe: true,
  3235. parent: 'div'
  3236. });
  3237. }, nullTools, selectiveCookies)
  3238. },
  3239.  
  3240. 'hdrezka.ag': () => {
  3241. Object.defineProperty(win, 'ab', {
  3242. value: false,
  3243. enumerable: true
  3244. });
  3245. gardener('div[id][onclick][onmouseup][onmousedown]', /onmouseout/i);
  3246. },
  3247.  
  3248. 'hqq.tv': () => scriptLander(() => {
  3249. // disable anti-debugging in hqq.tv player
  3250. 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);
  3251. deepWrapAPI(root => {
  3252. // skip obfuscated stuff and a few other calls
  3253. let _setInterval = root.setInterval,
  3254. _setTimeout = root.setTimeout;
  3255. root.setInterval = (...args) => {
  3256. let fun = args[0];
  3257. if (typeof fun === 'function') {
  3258. let text = _toString(fun),
  3259. skip = text.includes('check();') || isObfuscated(text);
  3260. _console.trace('setInterval', text, 'skip', skip);
  3261. if (skip) return -1;
  3262. }
  3263. return _setInterval.apply(this, args);
  3264. };
  3265. let wrappedST = new WeakSet();
  3266. root.setTimeout = (...args) => {
  3267. let fun = args[0];
  3268. if (typeof fun === 'function') {
  3269. let text = _toString(fun),
  3270. skip = fun.name === 'check' || isObfuscated(text);
  3271. if (!wrappedST.has(fun)) {
  3272. _console.trace('setTimeout', text, 'skip', skip);
  3273. wrappedST.add(fun);
  3274. }
  3275. if (skip) return;
  3276. }
  3277. return _setTimeout.apply(this, args);
  3278. };
  3279. // skip 'debugger' call
  3280. let _eval = root.eval;
  3281. root.eval = text => {
  3282. if (typeof text === 'string' && text.includes('debugger;')) {
  3283. _console.trace('skip eval', text);
  3284. return;
  3285. }
  3286. _eval(text);
  3287. };
  3288. // Prevent RegExpt + toString trick
  3289. let _proto;
  3290. try {
  3291. _proto = root.RegExp.prototype;
  3292. } catch (ignore) {
  3293. return;
  3294. }
  3295. let _RE_tS = Object.getOwnPropertyDescriptor(_proto, 'toString');
  3296. let _RE_tSV = _RE_tS.value || _RE_tS.get();
  3297. Object.defineProperty(_proto, 'toString', {
  3298. enumerable: _RE_tS.enumerable,
  3299. configurable: _RE_tS.configurable,
  3300. get() {
  3301. return _RE_tSV;
  3302. },
  3303. set(val) {
  3304. _console.trace('Attempt to change toString for', this, 'with', _toString(val));
  3305. }
  3306. });
  3307. });
  3308. }, deepWrapAPI),
  3309.  
  3310. 'hideip.me': {
  3311. now: () => scriptLander(() => {
  3312. let _innerHTML = Object.getOwnPropertyDescriptor(_Element, 'innerHTML');
  3313. let _set_innerHTML = _innerHTML.set;
  3314. let _innerText = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'innerText');
  3315. let _get_innerText = _innerText.get;
  3316. let div = _document.createElement('div');
  3317. _innerHTML.set = function (...args) {
  3318. _set_innerHTML.call(div, args[0].replace('i', 'a'));
  3319. if (args[0] && /[рp][еe]кл/.test(_get_innerText.call(div)) ||
  3320. /(\d\d\d?\.){3}\d\d\d?:\d/.test(_get_innerText.call(this))) {
  3321. _console.log('Anti-Adblock killed.');
  3322. return true;
  3323. }
  3324. _set_innerHTML.apply(this, args);
  3325. };
  3326. Object.defineProperty(_Element, 'innerHTML', _innerHTML);
  3327. Object.defineProperty(win, 'adblock', {
  3328. get() {
  3329. return false;
  3330. },
  3331. set() {},
  3332. enumerable: true
  3333. });
  3334. let _$ = {};
  3335. let _$_map = new WeakMap();
  3336. let _gOPD = Object.getOwnPropertyDescriptor(Object, 'getOwnPropertyDescriptor');
  3337. let _val_gOPD = _gOPD.value;
  3338. _gOPD.value = function (...args) {
  3339. let _res = _val_gOPD.apply(this, args);
  3340. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery')) {
  3341. delete _res.get;
  3342. delete _res.set;
  3343. _res.value = win[args[1]];
  3344. }
  3345. return _res;
  3346. };
  3347. Object.defineProperty(Object, 'getOwnPropertyDescriptor', _gOPD);
  3348. let getJQWrap = (n) => {
  3349. let name = n;
  3350. return {
  3351. enumerable: true,
  3352. get() {
  3353. return _$[name];
  3354. },
  3355. set(x) {
  3356. if (_$_map.has(x)) {
  3357. _$[name] = _$_map.get(x);
  3358. return true;
  3359. }
  3360. if (x === _$.$ || x === _$.jQuery) {
  3361. _$[name] = x;
  3362. return true;
  3363. }
  3364. _$[name] = new Proxy(x, {
  3365. apply(t, o, args) {
  3366. let _res = t.apply(o, args);
  3367. if (_$_map.has(_res.is))
  3368. _res.is = _$_map.get(_res.is);
  3369. else {
  3370. let _is = _res.is;
  3371. _res.is = function (...args) {
  3372. if (args[0] === ':hidden')
  3373. return false;
  3374. return _is.apply(this, args);
  3375. };
  3376. _$_map.set(_is, _res.is);
  3377. }
  3378. return _res;
  3379. }
  3380. });
  3381. _$_map.set(x, _$[name]);
  3382. return true;
  3383. }
  3384. };
  3385. };
  3386. Object.defineProperty(win, '$', getJQWrap('$'));
  3387. Object.defineProperty(win, 'jQuery', getJQWrap('jQuery'));
  3388. let _dP = Object.defineProperty;
  3389. Object.defineProperty = function (...args) {
  3390. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery'))
  3391. return undefined;
  3392. return _dP.apply(this, args);
  3393. };
  3394. })
  3395. },
  3396.  
  3397. 'igra-prestoloff.cx': () => scriptLander(() => {
  3398. /*jslint evil: true */ // yes, evil, I know
  3399. let _write = _document.write.bind(_document);
  3400. /*jslint evil: false */
  3401. nt.define('document.write', t => {
  3402. let id = t.match(/jwplayer\("(\w+)"\)/i);
  3403. if (id && id[1])
  3404. return _write(`<div id="${id[1]}"></div>${t}`);
  3405. return _write('');
  3406. }, {
  3407. enumerable: true
  3408. });
  3409. }),
  3410.  
  3411. 'imageban.ru': () => {
  3412. Object.defineProperty(win, 'V7x1J', {
  3413. get() {
  3414. return null;
  3415. }
  3416. });
  3417. },
  3418.  
  3419. 'inoreader.com': () => scriptLander(() => {
  3420. let i = setInterval(() => {
  3421. if ('adb_detected' in win) {
  3422. win.adb_detected = () => win.adb_not_detected();
  3423. clearInterval(i);
  3424. }
  3425. }, 10);
  3426. _document.addEventListener('DOMContentLoaded', () => clearInterval(i), false);
  3427. }),
  3428.  
  3429. 'it-actual.ru': () => scriptLander(() => {
  3430. abortExecution.onAll('blocked');
  3431. abortExecution.onGet('nsg');
  3432. }, abortExecution),
  3433.  
  3434. 'ivi.ru': () => {
  3435. let _xhr_open = win.XMLHttpRequest.prototype.open;
  3436. win.XMLHttpRequest.prototype.open = function (method, url, ...args) {
  3437. if (typeof url === 'string')
  3438. if (url.endsWith('/track'))
  3439. return;
  3440. return _xhr_open.call(this, method, url, ...args);
  3441. };
  3442. let _responseText = Object.getOwnPropertyDescriptor(XMLHttpRequest.prototype, 'responseText');
  3443. let _responseText_get = _responseText.get;
  3444. _responseText.get = function () {
  3445. if (this.__responseText__)
  3446. return this.__responseText__;
  3447. let res = _responseText_get.apply(this, arguments);
  3448. let o;
  3449. try {
  3450. if (res)
  3451. o = JSON.parse(res);
  3452. } catch (ignore) {}
  3453. let changed = false;
  3454. if (o && o.result) {
  3455. if (o.result instanceof Array &&
  3456. 'adv_network_logo_url' in o.result[0]) {
  3457. o.result = [];
  3458. changed = true;
  3459. }
  3460. if (o.result.show_adv) {
  3461. o.result.show_adv = false;
  3462. changed = true;
  3463. }
  3464. }
  3465. if (changed) {
  3466. _console.log('changed response >>', o);
  3467. res = JSON.stringify(o);
  3468. }
  3469. this.__responseText__ = res;
  3470. return res;
  3471. };
  3472. Object.defineProperty(XMLHttpRequest.prototype, 'responseText', _responseText);
  3473. },
  3474.  
  3475. 'kakprosto.ru': () => scriptLander(() => {
  3476. selectiveCookies('yadb');
  3477. abortExecution.inlineScript('yaProxy', {
  3478. pattern: /yadb/
  3479. });
  3480. abortExecution.inlineScript('yandexContextAsyncCallbacks');
  3481. abortExecution.inlineScript('adfoxAsyncParams');
  3482. abortExecution.inlineScript('adfoxBackGroundLoaded');
  3483. }, selectiveCookies, abortExecution),
  3484.  
  3485. 'kinopoisk.ru': () => {
  3486. // filter cookies
  3487. // set no-branding body style and adjust other blocks on the page
  3488. const style = {
  3489. '.app__header.app__header_margin-bottom_brand, #top': {
  3490. margin_bottom: '20px !important'
  3491. },
  3492. '.app__branding': {
  3493. display: 'none!important'
  3494. }
  3495. };
  3496. if (location.hostname === 'www.kinopoisk.ru' && !location.pathname.startsWith('/games/'))
  3497. style['html:not(#id), body:not(#id), .app-container'] = {
  3498. background: '#d5d5d5 url(/images/noBrandBg.jpg) 50% 0 no-repeat !important'
  3499. };
  3500. createStyle(style);
  3501. scriptLander(() => {
  3502. selectiveCookies('cmtchd|crookie|kpunk');
  3503. // filter JSON
  3504. win.JSON.parse = new Proxy(win.JSON.parse, {
  3505. apply(fun, that, args) {
  3506. let o = _apply(fun, that, args);
  3507. let name = 'antiAdBlockCookieName';
  3508. if (name in o && typeof o[name] === 'string')
  3509. selectiveCookies(o[name]);
  3510. name = 'branding';
  3511. if (name in o) o[name] = {};
  3512. // tricks against ads in the trailer player
  3513. // if (location.hostname.startsWith('widgets.'))
  3514. if (o.page && o.page.playerParams)
  3515. delete o.page.playerParams.adConfig;
  3516. if (o.common && o.common.bunker && o.common.bunker.adv && o.common.bunker.adv.filmIdWithoutAd)
  3517. o.common.bunker.adv.filmIdWithoutAd.includes = () => true;
  3518. //_console.log('JSON.parse', o);
  3519. return o;
  3520. }
  3521. });
  3522. // skip timeout check for blocked requests
  3523. win.setTimeout = new Proxy(win.setTimeout, {
  3524. apply(fun, that, args) {
  3525. if (args[1] === 100) {
  3526. let str = _toString(args[0]);
  3527. if (str.endsWith('{a()}') || str.endsWith('{n()}'))
  3528. return;
  3529. }
  3530. return _apply(fun, that, args);
  3531. }
  3532. });
  3533. // obfuscated Yandex.Direct
  3534. nt.define('Object.prototype.initYaDirect', undefined);
  3535. nt.define('Object.prototype._resolveDetectResult', () => null);
  3536. nt.define('Object.prototype.detectResultPromise', new Promise(r => r(false)));
  3537. if (location.hostname === 'www.kinopoisk.ru')
  3538. nt.define('Object.prototype.initAd', nt.func(undefined, 'initAd'));
  3539. // catch branding and other things
  3540. let _KP;
  3541. Object.defineProperty(win, 'KP', {
  3542. get() {
  3543. return _KP;
  3544. },
  3545. set(val) {
  3546. if (_KP === val)
  3547. return true;
  3548. _KP = new Proxy(val, {
  3549. set(kp, name, val) {
  3550. if (name === 'branding') {
  3551. kp[name] = new Proxy({
  3552. weborama: {}
  3553. }, {
  3554. get(kp, name) {
  3555. return name in kp ? kp[name] : '';
  3556. },
  3557. set() {}
  3558. });
  3559. return true;
  3560. }
  3561. if (name === 'config')
  3562. val = new Proxy(val, {
  3563. set(cfg, name, val) {
  3564. if (name === 'anContextUrl')
  3565. return true;
  3566. if (name === 'adfoxEnabled' || name === 'hasBranding')
  3567. val = false;
  3568. if (name === 'adfoxVideoAdUrls')
  3569. val = {
  3570. flash: {},
  3571. html: {}
  3572. };
  3573. cfg[name] = val;
  3574. return true;
  3575. }
  3576. });
  3577. kp[name] = val;
  3578. return true;
  3579. }
  3580. });
  3581. _console.log('KP =', val);
  3582. }
  3583. });
  3584. }, selectiveCookies, nullTools);
  3585. },
  3586.  
  3587. 'korrespondent.net': {
  3588. now: () => scriptLander(() => {
  3589. nt.define('holder', function (id) {
  3590. let div = _document.getElementById(id);
  3591. if (!div)
  3592. return;
  3593. if (div.parentNode.classList.contains('col__sidebar')) {
  3594. div.parentNode.appendChild(div);
  3595. div.style.height = '300px';
  3596. }
  3597. });
  3598. }, nullTools),
  3599. dom() {
  3600. for (let frame of _document.querySelectorAll('.unit-side-informer > iframe'))
  3601. frame.parentNode.style.width = '1px';
  3602. }
  3603. },
  3604.  
  3605. 'libertycity.ru': () => scriptLander(() => {
  3606. nt.define('adBlockEnabled', false);
  3607. }, nullTools),
  3608.  
  3609. 'liveinternet.ru': () => scriptLander(() => {
  3610. abortExecution.onGet('Object.prototype.initAd');
  3611. }, abortExecution),
  3612.  
  3613. 'livejournal.com': () => scriptLander(() => {
  3614. nt.define('Object.prototype.Adf', undefined);
  3615. nt.define('Object.prototype.Begun', undefined);
  3616. }, nullTools),
  3617.  
  3618. 'mail.ru': {
  3619. other: 'ok.ru, sportmail.ru',
  3620. now: () => scriptLander(() => {
  3621. const _hostparts = location.hostname.split('.');
  3622. const _subdomain = _hostparts.slice(-3).join('.');
  3623. const _hostname = _hostparts.slice(-2).join('.');
  3624. const _emailru = _subdomain === 'e.mail.ru' || _subdomain === 'octavius.mail.ru';
  3625. const _mymailru = _subdomain === 'my.mail.ru';
  3626. const _okru = _hostname === 'ok.ru';
  3627. // setTimeout filter
  3628. // advBlock|rbParams - ads
  3629. // document\.title= - blinking title on background news load on main page
  3630. const pattern = /advBlock|rbParams|document\.title=/i;
  3631. const _setTimeout = win.setTimeout;
  3632. win.setTimeout = function setTimeout(...args) {
  3633. let text = _toString(args[0]);
  3634. if (pattern.test(text)) {
  3635. _console.trace('Skipped setTimeout:', text);
  3636. return;
  3637. }
  3638. return _setTimeout(...args);
  3639. };
  3640.  
  3641. // Trick to prevent mail.ru from removing 3rd-party styles
  3642. nt.define('Object.prototype.restoreVisibility', nt.func(null, 'restoreVisibility'));
  3643. // Other Yandex Direct and other ads
  3644. nt.define('Object.prototype.initMimic', undefined);
  3645. nt.define('Object.prototype.hpConfig', undefined);
  3646. nt.define('Object.prototype.direct', undefined);
  3647. const getAds = () => new Promise(
  3648. r => r(nt.proxy({}, '?.getAds()'))
  3649. );
  3650. nt.define('Object.prototype.getAds', getAds);
  3651. nt.define('rb_counter', nt.func(null, 'rb_counter'));
  3652. if (_subdomain === 'mail.ru') { // main page
  3653. nt.define('Object.prototype.baits', undefined); // detector
  3654. nt.define('Object.prototype.getFeed', nt.func(null, 'pulse.getFeed')); // Pulse feed
  3655. createStyle('body > div > .pulse { display: none !important }');
  3656. }
  3657. if (_emailru)
  3658. nt.define('Object.prototype.show_me_ads', undefined);
  3659. else if (_mymailru)
  3660. nt.define('Object.prototype.runMimic', nt.func(null, 'runMimic'));
  3661. else {
  3662. nt.define('Object.prototype.mimic', undefined);
  3663. const xray = nt.func(undefined, 'xray');
  3664. nt.defineOn(xray, 'send', nt.func(undefined, 'xray.send'), 'xray.');
  3665. nt.defineOn(xray, 'radarPrefix', null, 'xray.');
  3666. nt.defineOn(xray, 'xrayRadarUrl', undefined, 'xray.');
  3667. nt.defineOn(xray, 'defaultParams', nt.proxy({
  3668. i: undefined,
  3669. p: 'media'
  3670. }), 'xray.');
  3671. nt.define('Object.prototype.xray', nt.proxy(xray));
  3672. }
  3673. // shenanigans against ok.ru ABP detector
  3674. if (_okru) {
  3675. abortExecution.onGet('OK.hooks');
  3676. // banners on ok.ru and counter
  3677. nt.define('getAdvTargetParam', nt.func(null, 'getAdvTargetParam'));
  3678. // break detection in case detector wasn't wrapped
  3679. abortExecution.onSet('Object.prototype.adBlockDetected');
  3680. }
  3681. // news.mail.ru and sportmail.ru
  3682. abortExecution.onGet('myWidget');
  3683. // cleanup e.mail.ru configs and mimic config on news and sport
  3684. const emptyString = (root, name) => root[name] && (root[name] = '');
  3685. const detectMimic = /direct|240x400|SlotView/;
  3686. win.JSON.parse = new Proxy(win.JSON.parse, {
  3687. apply(fun, that, args) {
  3688. let o = _apply(fun, that, args);
  3689. if (o && typeof o === 'object') {
  3690. if (o.cfg && o.cfg.sotaFeatures) {
  3691. let root = o.cfg.sotaFeatures;
  3692. if (Array.isArray(root.adv)) root.adv = [];
  3693. for (let name in root)
  3694. if (name.startsWith('adv-') || name.startsWith('adman-'))
  3695. delete root[name];
  3696. ['email_logs_to', 'smokescreen-locators'].forEach(name => emptyString(root, name));
  3697. }
  3698. if (o.userConfig) {
  3699. if (Array.isArray(o.userConfig.honeypot))
  3700. o.userConfig.honeypot.forEach((v, id, me) => (me[id] = []));
  3701. const cfg = o.userConfig.config;
  3702. if (cfg && cfg.honeypot)
  3703. emptyString(cfg.honeypot, 'baits');
  3704. }
  3705. if (o.body) {
  3706. const flags = o.body.common_purpose_flags;
  3707. if (flags && 'hide_ad_in_mail_web' in flags)
  3708. flags.hide_ad_in_mail_web = true;
  3709. if (o.body.show_me_ads)
  3710. o.body.show_me_ads = false;
  3711. }
  3712. //_console.log('JSON.parse', o);
  3713. }
  3714. if (Array.isArray(o))
  3715. if (o.some(t => typeof t === 'string' && detectMimic.test(t))) {
  3716. _console.log('Replaced', o);
  3717. o = [];
  3718. } //else _console.log('JSON.parse', o);
  3719. return o;
  3720. }
  3721. });
  3722. // all the rest is only needed on main page and in emails
  3723. if (_subdomain !== 'mail.ru' && !_emailru && !_okru)
  3724. return;
  3725.  
  3726. // Disable page scrambler on mail.ru to let extensions easily block ads there
  3727. let logger = {
  3728. apply(fun, that, args) {
  3729. let res = _apply(fun, that, args);
  3730. _console.log(`${fun._name}(`, ...args, `)\n>>`, res);
  3731. return res;
  3732. }
  3733. };
  3734.  
  3735. function wrapLocator(locator) {
  3736. if ('setup' in locator) {
  3737. let _setup = locator.setup;
  3738. locator.setup = function (o) {
  3739. if ('enable' in o) {
  3740. o.enable = false;
  3741. _console.log('Disable mimic mode.');
  3742. }
  3743. if ('links' in o) {
  3744. o.links = [];
  3745. _console.log('Call with empty list of sheets.');
  3746. }
  3747. return _setup.call(this, o);
  3748. };
  3749. locator.insertSheet = () => false;
  3750. locator.wrap = () => false;
  3751. }
  3752. try {
  3753. let names = [];
  3754. for (let name in locator)
  3755. if (typeof locator[name] === 'function' && name !== 'transform') {
  3756. locator[name]._name = "locator." + name;
  3757. locator[name] = new Proxy(locator[name], logger);
  3758. names.push(name);
  3759. }
  3760. _console.log(`[locator] wrapped properties: ${names.length ? names.join(', ') : '[empty]'}`);
  3761. } catch (e) {
  3762. _console.log(e);
  3763. }
  3764. return locator;
  3765. }
  3766.  
  3767. function defineLocator(root) {
  3768. let _locator = root.locator;
  3769. let wrapLocatorSetter = vl => _locator = wrapLocator(vl);
  3770. let loc_desc = Object.getOwnPropertyDescriptor(root, 'locator');
  3771. if (!loc_desc || loc_desc.set !== wrapLocatorSetter)
  3772. try {
  3773. Object.defineProperty(root, 'locator', {
  3774. set: wrapLocatorSetter,
  3775. get() {
  3776. return _locator;
  3777. }
  3778. });
  3779. } catch (err) {
  3780. _console.log('Unable to redefine "locator" object!!!', err);
  3781. }
  3782. if (loc_desc.value)
  3783. _locator = wrapLocator(loc_desc.value);
  3784. }
  3785.  
  3786. { // auto-stubs for various ad, detection and obfuscation modules
  3787. const missingCheck = {
  3788. get(obj, name) {
  3789. let res = obj[name];
  3790. if (!(name in obj))
  3791. _console.trace(`Missing "${name}" in`, obj);
  3792. return res;
  3793. }
  3794. };
  3795. const skipLog = (name, ret) => (...args) => (_console.log(`${name}(`, ...args, ')'), ret);
  3796. const createSkipAllObject = (baseName, obj = {
  3797. __esModule: true
  3798. }) => new Proxy(obj, {
  3799. get(obj, name) {
  3800. if (name in obj)
  3801. return obj[name];
  3802. _console.log(`Created stub for "${name}" in ${baseName}.`);
  3803. obj[name] = skipLog(`${baseName}.${name}`);
  3804. return obj[name];
  3805. },
  3806. set() {}
  3807. });
  3808. const redefiner = {
  3809. apply(fun, that, args) {
  3810. let res;
  3811. let warn = false;
  3812. let name = fun._name;
  3813. if (name === 'mrg-smokescreen/Welter')
  3814. res = {
  3815. isWelter() {
  3816. return true;
  3817. },
  3818. wrap: skipLog(`${name}.wrap`)
  3819. };
  3820. if (name === 'mrg-smokescreen/Honeypot')
  3821. res = {
  3822. check(...args) {
  3823. _console.log(`${name}.check(`, ...args, ')');
  3824. return new Promise(() => undefined);
  3825. },
  3826. version: "-1"
  3827. };
  3828. if (name === 'advert/adman/adman') {
  3829. let features = {
  3830. siteZones: {},
  3831. slots: {}
  3832. };
  3833. [
  3834. 'expId', 'siteId', 'mimicEndpoint', 'mimicPartnerId',
  3835. 'immediateFetchTimeout', 'delayedFetchTimeout'
  3836. ].forEach(name => void(features[name] = null));
  3837. res = createSkipAllObject(name, {
  3838. getFeatures: skipLog(`${name}.getFeatures`, features)
  3839. });
  3840. }
  3841. if (name === 'mrg-smokescreen/Utils')
  3842. res = createSkipAllObject(name, {
  3843. extend(...args) {
  3844. let res = {
  3845. enable: false,
  3846. match: [],
  3847. links: []
  3848. };
  3849. _console.log(`${name}.extend(`, ...args, ') >>', res);
  3850. return res;
  3851. }
  3852. });
  3853. if (name.startsWith('OK/banners/') ||
  3854. name.startsWith('mrg-smokescreen/StyleSheets') ||
  3855. name === '@mail/mimic' ||
  3856. name === 'mediator/advert-managers')
  3857. res = createSkipAllObject(name);
  3858. if (res) {
  3859. Object.defineProperty(res, Symbol.toStringTag, {
  3860. get() {
  3861. return `Skiplog object for ${name}`;
  3862. }
  3863. });
  3864. Object.defineProperty(res, Symbol.toPrimitive, {
  3865. value(hint) {
  3866. if (hint === 'string')
  3867. return Object.prototype.toString.call(this);
  3868. return `[missing toPrimitive] ${name} ${hint}`;
  3869. }
  3870. });
  3871. res = new Proxy(res, missingCheck);
  3872. } else {
  3873. res = _apply(fun, that, args);
  3874. warn = true;
  3875. }
  3876. _console[warn ? 'warn' : 'log'](name, '(', ...args, ')\n>>', res);
  3877. return res;
  3878. }
  3879. };
  3880.  
  3881. const advModuleNamesStartWith = /^(mrg-(context|honeypot)|adv\/)/;
  3882. const advModuleNamesGeneric = /advert|banner|mimic|smoke/i;
  3883. const wrapAdFuncs = {
  3884. apply(fun, that, args) {
  3885. let module = args[0];
  3886. if (typeof module === 'string')
  3887. if ((advModuleNamesStartWith.test(module) ||
  3888. advModuleNamesGeneric.test(module)) &&
  3889. // fix for e.mail.ru in Fx56 and below, looks like Proxy is quirky there
  3890. !module.startsWith('patron.v2.')) {
  3891. let main = args[args.length - 1];
  3892. main._name = module;
  3893. args[args.length - 1] = new Proxy(main, redefiner);
  3894. }
  3895. return _apply(fun, that, args);
  3896. }
  3897. };
  3898. const wrapDefine = def => {
  3899. if (!def)
  3900. return;
  3901. _console.log('define =', def);
  3902. def = new Proxy(def, wrapAdFuncs);
  3903. def._name = 'define';
  3904. return def;
  3905. };
  3906. let _define = wrapDefine(win.define);
  3907. Object.defineProperty(win, 'define', {
  3908. get() {
  3909. return _define;
  3910. },
  3911. set(x) {
  3912. if (_define === x)
  3913. return true;
  3914. _define = wrapDefine(x);
  3915. return true;
  3916. }
  3917. });
  3918. }
  3919.  
  3920. let _honeyPot;
  3921.  
  3922. function defineDetector(mr) {
  3923. let __ = mr._ || {};
  3924. let setHoneyPot = o => {
  3925. if (!o || o === _honeyPot) return;
  3926. _console.log('[honeyPot]', o);
  3927. _honeyPot = function () {
  3928. this.check = new Proxy(() => {
  3929. __.STUCK_IN_POT = false;
  3930. return false;
  3931. }, logger);
  3932. this.check._name = 'honeyPot.check';
  3933. this.destroy = () => null;
  3934. };
  3935. };
  3936. if ('honeyPot' in mr)
  3937. setHoneyPot(mr.honeyPot);
  3938. else
  3939. Object.defineProperty(mr, 'honeyPot', {
  3940. get() {
  3941. return _honeyPot;
  3942. },
  3943. set: setHoneyPot
  3944. });
  3945.  
  3946. __ = new Proxy(__, {
  3947. get(target, prop) {
  3948. return target[prop];
  3949. },
  3950. set(target, prop, val) {
  3951. _console.log(`mr._.${prop} =`, val);
  3952. target[prop] = val;
  3953. return true;
  3954. }
  3955. });
  3956. mr._ = __;
  3957. }
  3958.  
  3959. function defineAdd(mr) {
  3960. let _add;
  3961. let addWrapper = {
  3962. apply(fun, that, args) {
  3963. let module = args[0];
  3964. if (typeof module === 'string' && module.startsWith('ad')) {
  3965. _console.log('Skip module:', module);
  3966. return;
  3967. }
  3968. if (typeof module === 'object' && module.name.startsWith('ad'))
  3969. _console.log('Loaded module:', module);
  3970. return logger.apply(fun, that, args);
  3971. }
  3972. };
  3973. let setMrAdd = v => {
  3974. if (!v) return;
  3975. v._name = 'mr.add';
  3976. v = new Proxy(v, addWrapper);
  3977. _add = v;
  3978. };
  3979. if ('add' in mr)
  3980. setMrAdd(mr.add);
  3981. Object.defineProperty(mr, 'add', {
  3982. get() {
  3983. return _add;
  3984. },
  3985. set: setMrAdd
  3986. });
  3987.  
  3988. }
  3989.  
  3990. const _mr_wrapper = vl => {
  3991. defineLocator(vl.mimic ? vl.mimic : vl);
  3992. defineDetector(vl);
  3993. defineAdd(vl);
  3994. return vl;
  3995. };
  3996. if ('mr' in win) {
  3997. _console.log('Found existing "mr" object.');
  3998. win.mr = _mr_wrapper(win.mr);
  3999. } else {
  4000. let _mr;
  4001. Object.defineProperty(win, 'mr', {
  4002. get() {
  4003. return _mr;
  4004. },
  4005. set(vl) {
  4006. _mr = vl ? _mr_wrapper(vl) : vl;
  4007. },
  4008. configurable: true
  4009. });
  4010. let _defineProperty = _bindCall(Object.defineProperty);
  4011. Object.defineProperty = function defineProperty(...args) {
  4012. const [obj, name, conf] = args;
  4013. if (name === 'mr' && obj instanceof Window) {
  4014. _console.trace('Object.defineProperty(', ...args, ')');
  4015. conf.set(_mr_wrapper(conf.get()));
  4016. }
  4017. if ((name === 'honeyPot' || name === 'add') && _mr === obj && conf.set)
  4018. return;
  4019. return _defineProperty(this, ...args);
  4020. };
  4021. }
  4022. }, nullTools, selectiveCookies, abortExecution)
  4023. },
  4024.  
  4025. 'oms.matchat.online': () => scriptLander(() => {
  4026. let _rmpGlobals;
  4027. Object.defineProperty(win, 'rmpGlobals', {
  4028. get() {
  4029. return _rmpGlobals;
  4030. },
  4031. set(val) {
  4032. if (val === _rmpGlobals)
  4033. return true;
  4034. _rmpGlobals = new Proxy(val, {
  4035. get(obj, name) {
  4036. if (name === 'adBlockerDetected')
  4037. return false;
  4038. return obj[name];
  4039. },
  4040. set(obj, name, val) {
  4041. if (name === 'adBlockerDetected')
  4042. _console.trace('rmpGlobals.adBlockerDetected =', val);
  4043. else
  4044. obj[name] = val;
  4045. return true;
  4046. }
  4047. });
  4048. }
  4049. });
  4050. }),
  4051.  
  4052. 'megogo.net': {
  4053. now() {
  4054. nt.define('adBlock', false);
  4055. nt.define('showAdBlockMessage', nt.func(null, 'showAdBlockMessage'));
  4056. }
  4057. },
  4058.  
  4059. 'naruto-base.su': () => gardener('div[id^="entryID"],.block', /href="http.*?target="_blank"/i),
  4060.  
  4061. 'otzovik.com': () => scriptLander(() => {
  4062. abortExecution.onGet('Object.prototype.DirectManagerStart');
  4063. abortExecution.onGet('Object.prototype._visibilityConfirmer');
  4064. let _o_math = win.o_math;
  4065. Object.defineProperty(win, 'o_math', {
  4066. get() {
  4067. return _o_math;
  4068. },
  4069. set(val) {
  4070. delete val.ext_uid;
  4071. _o_math = val;
  4072. }
  4073. });
  4074. }, abortExecution, selectiveCookies),
  4075.  
  4076. 'overclockers.ru': {
  4077. now() {
  4078. abortExecution.onAll('cardinals');
  4079. abortExecution.inlineScript('Document.prototype.createElement', {
  4080. pattern: /mamydirect/
  4081. });
  4082. }
  4083. },
  4084.  
  4085. 'peka2.tv': () => {
  4086. let bodyClass = 'body--branding';
  4087. let checkNode = node => {
  4088. for (let className of node.classList)
  4089. if (className.includes('banner') || className === bodyClass) {
  4090. _removeAttribute(node, 'style');
  4091. node.classList.remove(className);
  4092. for (let attr of Array.from(node.attributes))
  4093. if (attr.name.startsWith('advert'))
  4094. _removeAttribute(node, attr.name);
  4095. }
  4096. };
  4097. (new MutationObserver(ms => {
  4098. let m, node;
  4099. for (m of ms)
  4100. for (node of m.addedNodes)
  4101. if (node instanceof HTMLElement)
  4102. checkNode(node);
  4103. })).observe(_de, {
  4104. childList: true,
  4105. subtree: true
  4106. });
  4107. (new MutationObserver(ms => {
  4108. for (let m of ms)
  4109. checkNode(m.target);
  4110. })).observe(_de, {
  4111. attributes: true,
  4112. subtree: true,
  4113. attributeFilter: ['class']
  4114. });
  4115. },
  4116.  
  4117. 'pikabu.ru': () => gardener('.story', /story__author[^>]+>ads</i, {
  4118. root: '.inner_wrap',
  4119. observe: true
  4120. }),
  4121.  
  4122. 'piratbit.tld': {
  4123. other: 'pb.wtf',
  4124. dom() {
  4125. const remove = node => node && node.parentNode && (_console.log('removed', node), node.parentNode.removeChild(node));
  4126. const isAdLink = el => location.hostname === el.hostname && /^\/(\w{3}|exit|out)\/[\w=/]{20,}$/.test(el.pathname);
  4127. // line above topic content and images in the slider in the header
  4128. for (let el of _document.querySelectorAll('.releas-navbar div a, #page_contents a'))
  4129. if (isAdLink(el))
  4130. remove(el.closest('tr[class]:not(.top_line):not(.active), .row2[id^="post_"]') || el.closest('div[style]:not(.row1):not(.btn-group)'));
  4131. }
  4132. },
  4133.  
  4134. 'pixelexperience.org': () => scriptLander(() => {
  4135. abortExecution.inlineScript('eval', {
  4136. pattern: /blockadblock/
  4137. });
  4138. }, abortExecution),
  4139.  
  4140. 'player.starlight.digital': {
  4141. other: 'teleportal.ua',
  4142. dom() {
  4143. scriptLander(() => {
  4144. let _currVideo = win.currVideo;
  4145. Object.defineProperty(win, 'currVideo', {
  4146. get() {
  4147. return _currVideo;
  4148. },
  4149. set(val) {
  4150. _console.log('currVideo =', val);
  4151. if ('adv' in val)
  4152. val.adv.creatives = [];
  4153. if ('showadv' in val)
  4154. val.showadv = false;
  4155. if ('mediaHls' in val)
  4156. val.mediaHls = val.mediaHls.replace('adv=1', 'adv=0');
  4157. if ('media' in val)
  4158. for (let media of val.media)
  4159. media.url = media.url.replace('adv=1', 'adv=0');
  4160. _currVideo = val;
  4161. }
  4162. });
  4163. nt.define('Object.prototype.isAdBlockEnabled', false);
  4164. nt.define('Object.prototype.AdBlockDynamicConfig', undefined);
  4165. nt.define('ADT_PLAYER_ADBLOCK_CONFIG', '');
  4166. nt.define('ADT_PLAYER_ADBLOCK_CONFIG_DETECT_ON_FAIL', false);
  4167. }, nullTools);
  4168. }
  4169. },
  4170.  
  4171. 'qrz.ru': {
  4172. now() {
  4173. nt.define('ab', false);
  4174. nt.define('tryMessage', nt.func(null, 'tryMessage'));
  4175. }
  4176. },
  4177.  
  4178. 'rambler.ru': {
  4179. other: [
  4180. 'autorambler.ru', 'championat.com', 'eda.ru', 'gazeta.ru', 'lenta.ru', 'letidor.ru',
  4181. 'media.eagleplatform.com', 'motor.ru', 'passion.ru', 'quto.ru', 'rns.online', 'wmj.ru'
  4182. ].join(','),
  4183. now() {
  4184. scriptLander(() => {
  4185. // Skip login form and frames, and comments frames. Nothing to do here.
  4186. if (['id.rambler.ru', 'comments.rambler.ru'].includes(location.hostname))
  4187. return;
  4188.  
  4189. // prevent autoplay
  4190. if (location.hostname === 'vp.rambler.ru') {
  4191. nt.define('Object.prototype.VIEWPORT_VISIBLE_AREA_CHANGED', () => false);
  4192. return;
  4193. }
  4194. if (location.hostname.endsWith('.media.eagleplatform.com')) {
  4195. const _stopImmediatePropagation = _bindCall(Event.prototype.stopImmediatePropagation);
  4196. win.addEventListener('message', e => {
  4197. if (typeof e.data === 'object' && e.data.visible)
  4198. _stopImmediatePropagation(e);
  4199. });
  4200. return;
  4201. }
  4202. /* jshint -W001 */ // aka 'hasOwnProperty' is a really bad name, but this is a wrapper
  4203. const autoList = new Set(['autoplay', 'scrollplay']);
  4204. win.Object.prototype.hasOwnProperty = new Proxy(win.Object.prototype.hasOwnProperty, {
  4205. apply(fun, that, args) {
  4206. if (autoList.has(args[0]))
  4207. return false;
  4208. return _apply(fun, that, args);
  4209. }
  4210. });
  4211. /* jshint +W001 */
  4212.  
  4213. selectiveCookies('detect_count|dv|dvr|lv|lvr');
  4214. // Wrapper for adv loader settings in QW50aS1BZEJsb2Nr['7t7hystz']
  4215. const _contexts = new WeakMap();
  4216. Object.defineProperty(Object.prototype, 'Settings', {
  4217. set(val) {
  4218. if (typeof val === 'object' && 'Transports' in val && 'Urls' in val)
  4219. val.Urls = [];
  4220. _contexts.set(this, val);
  4221. },
  4222. get() {
  4223. return _contexts.get(this);
  4224. }
  4225. });
  4226. // disable video pop-outs in articles on gazeta.ru
  4227. if (location.hostname === 'gazeta.ru' || location.hostname.endsWith('.gazeta.ru'))
  4228. nt.define('creepyVideo', nt.func(null, 'creepyVideo'));
  4229. // disable Alice popup (encountered on horoscopes.rambler.ru)
  4230. nt.define('Object.prototype.needShowAlicePopup', false);
  4231. // disable some logging
  4232. yandexRavenStub();
  4233. // hide "disable ads" button
  4234. createStyle('a[href^="https://prime.rambler.ru/promo/"] { display: none !important }');
  4235. // prevent ads from loading
  4236. abortExecution.onGet('g_GazetaNoExchange');
  4237.  
  4238. //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;
  4239. const scriptSkipList = /nrWrapper|\/(desktopVendor|vendorsDesktop)\.|<anonymous>/;
  4240. const isLocalScript = (log) => {
  4241. let e = removeOwnFootprint(new Error()),
  4242. parts = e.stack.split(/\n/),
  4243. row = 0;
  4244. if (!/http/.test(parts[row]))
  4245. row += 1;
  4246. while (scriptSkipList.test(parts[row]))
  4247. row += 1;
  4248. let parse = /(https?:.*):\d+:\d+/.exec(parts[row]);
  4249. if (log)
  4250. _console.log(parse && parse[1] === location.href, parts[row], [parts]);
  4251. return parse && parse[1] === location.href;
  4252. };
  4253. const cutoff = 200;
  4254. const fts = f => _toString(f.__sentry__ && f.__sentry_original__ || f['nr@original'] || f);
  4255. win.setTimeout = new Proxy(win.setTimeout, {
  4256. apply(fun, that, args) {
  4257. if (isLocalScript()) {
  4258. const [callback, delay] = args;
  4259. const str = fts(callback);
  4260. if (!/\n/.test(str)) {
  4261. _console.trace(`Skipped setTimeout(${str.slice(0, cutoff)}${str.length > cutoff ? '\u2026' : ''}, ${delay})`);
  4262. return null;
  4263. }
  4264. }
  4265. return _apply(fun, that, args);
  4266. }
  4267. });
  4268. const _onerror = Object.getOwnPropertyDescriptor(win.HTMLElement.prototype, 'onerror');
  4269. _onerror.set = new Proxy(_onerror.set, {
  4270. apply(fun, that, args) {
  4271. if (typeof args[0] === 'function' && isLocalScript()) {
  4272. const str = fts(args[0]);
  4273. _console.trace(`Skipped onerror = ${str.slice(0, cutoff)}${str.length > cutoff ? '\u2026' : ''}`);
  4274. return;
  4275. }
  4276. return _apply(fun, that, args);
  4277. }
  4278. });
  4279. Object.defineProperty(win.HTMLElement.prototype, 'onerror', _onerror);
  4280. // Skip dev console check
  4281. win.console.debug = new Proxy(win.console.debug, {
  4282. apply(fun, that, args) {
  4283. if (args[0] instanceof HTMLImageElement)
  4284. return;
  4285. return _apply(fun, that, args);
  4286. }
  4287. });
  4288. // anti-abdetector
  4289. let _primeStorage;
  4290. Object.defineProperty(win, 'primeStorage', {
  4291. get() {
  4292. if (isLocalScript())
  4293. throw removeOwnFootprint(new TypeError(`Cannot read property 'primeStorage' of undefined`));
  4294. return _primeStorage;
  4295. },
  4296. set(val) {
  4297. _primeStorage = val;
  4298. }
  4299. });
  4300. // Defense against triggered detector
  4301. _Node.removeChild = new Proxy(_Node.removeChild, {
  4302. apply(fun, that, args) {
  4303. const [el] = args;
  4304. if (el.tagName === 'LINK' && isLocalScript()) {
  4305. _console.log(`Let's not remove ${el.tagName}.`);
  4306. return;
  4307. }
  4308. return _apply(fun, that, args);
  4309. }
  4310. });
  4311. }, nullTools, yandexRavenStub, selectiveCookies, abortExecution);
  4312. },
  4313. dom() {
  4314. // disable video pop-outs in articles on lenta.ru and rambler.ru
  4315. let domain = location.hostname.split('.');
  4316. if (['lenta', 'rambler'].includes(domain[domain.length - 2])) {
  4317. const player = _document.querySelector('.js-video-box__container, .j-mini-player__video');
  4318. if (player) player.removeAttribute('class');
  4319. }
  4320. // remove utm_ form links
  4321. const parser = _document.createElement('a');
  4322. _document.addEventListener('mousedown', (e) => {
  4323. let t = e.target;
  4324. if (!t.href)
  4325. t = t.closest('A');
  4326. if (t && t.href) {
  4327. parser.href = t.href;
  4328. let remove = [];
  4329. let params = parser.search.slice(1).split('&').filter(name => {
  4330. if (name.startsWith('utm_')) {
  4331. remove.push(name);
  4332. return false;
  4333. }
  4334. return true;
  4335. });
  4336. if (remove.length)
  4337. _console.log('Removed parameters from link:', ...remove);
  4338. if (params.length)
  4339. parser.search = `?${params.join('&')}`;
  4340. else
  4341. parser.search = '';
  4342. t.href = parser.href;
  4343. }
  4344. }, false);
  4345. }
  4346. },
  4347.  
  4348. 'razlozhi.ru': {
  4349. now() {
  4350. nt.define('cadb', false);
  4351. for (let func of ['createShadowRoot', 'attachShadow'])
  4352. if (func in _Element)
  4353. _Element[func] = function () {
  4354. return this.cloneNode();
  4355. };
  4356. }
  4357. },
  4358.  
  4359. 'rbc.ru': {
  4360. other: 'autonews.ru, rbcplus.ru, sportrbc.ru',
  4361. now() {
  4362. scriptLander(() => selectiveCookies('adb_on'), selectiveCookies);
  4363. let _RA;
  4364. let setArgs = {
  4365. 'showBanners': true,
  4366. 'showAds': true,
  4367. 'banners.staticPath': '',
  4368. 'paywall.staticPath': '',
  4369. 'banners.dfp.config': [],
  4370. 'banners.dfp.pageTargeting': () => null,
  4371. };
  4372. Object.defineProperty(win, 'RA', {
  4373. get() {
  4374. return _RA;
  4375. },
  4376. set(vl) {
  4377. _console.log('RA =', vl);
  4378. if ('repo' in vl) {
  4379. _console.log('RA.repo =', vl.repo);
  4380. vl.repo = new Proxy(vl.repo, {
  4381. set(obj, name, val) {
  4382. if (name === 'banner') {
  4383. _console.log(`RA.repo.${name} =`, val);
  4384. val = new Proxy(val, {
  4385. get(obj, name) {
  4386. let res = obj[name];
  4387. if (typeof obj[name] === 'function') {
  4388. res = () => undefined;
  4389. if (name === 'getService')
  4390. res = service => {
  4391. if (service === 'dfp')
  4392. return {
  4393. getPlaces() {
  4394. return;
  4395. },
  4396. createPlaceholder() {
  4397. return;
  4398. }
  4399. };
  4400. return undefined;
  4401. };
  4402. res.toString = obj[name].toString.bind(obj[name]);
  4403. }
  4404. if (name === 'isInited')
  4405. res = true;
  4406. _console.trace(`get RA.repo.banner.${name}`, res);
  4407. return res;
  4408. }
  4409. });
  4410. }
  4411. obj[name] = val;
  4412. return true;
  4413. }
  4414. });
  4415. } else
  4416. _console.log('Unable to locate RA.repo');
  4417. _RA = new Proxy(vl, {
  4418. set(o, name, val) {
  4419. if (name === 'config') {
  4420. _console.log('RA.config =', val);
  4421. if ('set' in val) {
  4422. val.set = new Proxy(val.set, {
  4423. apply(set, that, args) {
  4424. let name = args[0];
  4425. if (name in setArgs)
  4426. args[1] = setArgs[name];
  4427. if (name in setArgs || name === 'checkad')
  4428. _console.log('RA.config.set(', ...args, ')');
  4429. return _apply(set, that, args);
  4430. }
  4431. });
  4432. val.set('showAds', true); // pretend ads already were shown
  4433. }
  4434. }
  4435. o[name] = val;
  4436. return true;
  4437. }
  4438. });
  4439. }
  4440. });
  4441. Object.defineProperty(win, 'bannersConfig', {
  4442. set() {},
  4443. get() {
  4444. return [];
  4445. }
  4446. });
  4447. // pretend there is a paywall landing on screen already
  4448. let pwl = _document.createElement('div');
  4449. pwl.style.display = 'none';
  4450. pwl.className = 'js-paywall-landing';
  4451. _document.documentElement.appendChild(pwl);
  4452. // detect and skip execution of one of the ABP detectors
  4453. win.setTimeout = new Proxy(win.setTimeout, {
  4454. apply(fun, that, args) {
  4455. if (typeof args[0] === 'function') {
  4456. let fts = _toString(args[0]);
  4457. if (/\.length\s*>\s*0\s*&&/.test(fts) && /:hidden/.test(fts)) {
  4458. _console.log('Skipped setTimout(', fts, args[1], ')');
  4459. return;
  4460. }
  4461. }
  4462. return _apply(fun, that, args);
  4463. }
  4464. });
  4465. // hide banner placeholders
  4466. createStyle('[data-banner-id], .banner__container, .banners__yandex__article { display: none !important }');
  4467. },
  4468. dom() {
  4469. // hide sticky banner place at the top of the page
  4470. for (let itm of _document.querySelectorAll('.l-sticky'))
  4471. if (itm.querySelector('.banner__container__link'))
  4472. itm.style.display = 'none';
  4473. }
  4474. },
  4475.  
  4476. 'reactor.cc': {
  4477. other: 'joyreactor.cc, pornreactor.cc',
  4478. now: () => scriptLander(() => {
  4479. selectiveEval();
  4480. win.open = function () {
  4481. throw new ReferenceError('Redirect prevention.');
  4482. };
  4483. nt.define('Worker', nt.func(nt.proxy({}, 'Worker'), 'Worker'));
  4484. let _CTRManager = win.CTRManager;
  4485. Object.defineProperty(win, 'CTRManager', {
  4486. get() {
  4487. return _CTRManager;
  4488. },
  4489. set(vl) {
  4490. if (vl === _CTRManager)
  4491. return true;
  4492. _CTRManager = {};
  4493. for (let name in vl)
  4494. if (typeof vl[name] !== 'function')
  4495. _CTRManager[name] = vl[name];
  4496. _CTRManager = nt.proxy(_CTRManager, 'CTRManager');
  4497. }
  4498. });
  4499. }, nullTools, selectiveEval),
  4500. click(e) {
  4501. let node = e.target;
  4502. if (node.nodeType === _Node.ELEMENT_NODE &&
  4503. node.style.position === 'absolute' &&
  4504. node.style.zIndex > 0)
  4505. node.parentNode.removeChild(node);
  4506. }
  4507. },
  4508.  
  4509. 'rp5.tld': {
  4510. now() {
  4511. Object.defineProperty(win, 'sContentBottom', {
  4512. set() {},
  4513. get() {
  4514. return '';
  4515. }
  4516. });
  4517. // skip timeout check for blocked requests
  4518. let _setTimeout = win.setTimeout;
  4519. win.setTimeout = function setTimeout(...args) {
  4520. let str = (typeof args[0] === 'string' ? args[0] : _toString(args[0]));
  4521. if (str.includes('xvb')) {
  4522. _console.log('Blocked setTimeout for:', str);
  4523. return;
  4524. }
  4525. return _setTimeout(...args);
  4526. };
  4527. },
  4528. dom() {
  4529. let node = selectNodeByTextContent('Разместить текстовое объявление', {
  4530. root: _de.querySelector('#content-wrapper'),
  4531. shallow: true
  4532. });
  4533. if (node)
  4534. node.style.display = 'none';
  4535. }
  4536. },
  4537.  
  4538. 'rsload.net': {
  4539. load() {
  4540. let dis = _document.querySelector('label[class*="cb-disable"]');
  4541. if (dis)
  4542. dis.click();
  4543. },
  4544. click(e) {
  4545. let t = e.target;
  4546. if (t && t.href && (/:\/\/\d+\.\d+\.\d+\.\d+\//.test(t.href)))
  4547. t.href = t.href.replace('://', '://rsload.net:rsload.net@');
  4548. }
  4549. },
  4550.  
  4551. 'rustorka.tld': {
  4552. other: [
  4553. 'rustorka.innal.top, rustorka2.innal.top, rustorka3.innal.top',
  4554. 'rustorka4.innal.top, rustorka5.innal.top, rustorka6.innal.top',
  4555. 'rustorka.naylo.top'
  4556. ].join(', '),
  4557. now: () => scriptLander(() => {
  4558. selectiveCookies('~default|(?!(PHPSESSID|__cfduid|announcements|bb_data|bb_t|id|opt_js|shout)$).*');
  4559. selectiveEval(/antiadblock/);
  4560. abortExecution.onGet('ads_script');
  4561. abortExecution.inlineScript('setTimeout', {
  4562. pattern: /("(\\x[0-9A-F]{2})+",\s?){4}/
  4563. });
  4564.  
  4565. const _doc_proto = ('cookie' in _Document) ? _Document : Object.getPrototypeOf(_document);
  4566. const _cookie = Object.getOwnPropertyDescriptor(_doc_proto, 'cookie');
  4567.  
  4568. if (_cookie && GM.info.scriptHandler) {
  4569. const asyncCookieCleaner = () => {
  4570. GM.cookie.list({
  4571. url: location.href
  4572. }).then(cookies => {
  4573. for (let cookie of (cookies || []))
  4574. if (cookie.name === cookie.value) {
  4575. GM.cookie.delete(cookie);
  4576. _console.log(`Removed cookie: ${cookie.name}=${cookie.value}`);
  4577. }
  4578. });
  4579. };
  4580. _cookie.get = new Proxy(_cookie.get, {
  4581. apply(fun, that, args) {
  4582. asyncCookieCleaner();
  4583. return _apply(fun, that, args);
  4584. }
  4585. });
  4586. _cookie.set = new Proxy(_cookie.set, {
  4587. apply(fun, that, args) {
  4588. _apply(fun, that, args);
  4589. asyncCookieCleaner();
  4590. return true;
  4591. }
  4592. });
  4593. Object.defineProperty(_doc_proto, 'cookie', _cookie);
  4594. }
  4595. }, selectiveCookies, abortExecution),
  4596. dom: () => _document.cookie.slice(0, 0)
  4597. },
  4598.  
  4599. 'rutube.ru': () => scriptLander(() => {
  4600. jsonFilter('creative', 'creative.id');
  4601. jsonFilter('interactives', 'interactives.0');
  4602. }, jsonFilter),
  4603.  
  4604. 'sdamgia.ru': () => scriptLander(() => {
  4605. abortExecution.onGet('Object.prototype.getYa');
  4606. abortExecution.onGet('Object.prototype.initYa');
  4607. abortExecution.onGet('Object.prototype.initYaDirect');
  4608. }, abortExecution),
  4609.  
  4610. 'simpsonsua.com.ua': {
  4611. other: 'simpsonsua.tv',
  4612. now: () => scriptLander(() => {
  4613. let _addEventListener = _Document.addEventListener;
  4614. _document.addEventListener = function (event, callback) {
  4615. if (event === 'DOMContentLoaded' && callback.toString().includes('show_warning'))
  4616. return;
  4617. return _addEventListener.apply(this, arguments);
  4618. };
  4619. nt.define('need_warning', 0);
  4620. nt.define('onYouTubeIframeAPIReady', nt.func(null, 'onYouTubeIframeAPIReady'));
  4621. }, nullTools)
  4622. },
  4623.  
  4624. 'smotret-anime-365.ru': () => scriptLander(() => {
  4625. deepWrapAPI(root => {
  4626. const _pause = _bindCall(root.Audio.prototype.pause);
  4627. const _addEventListener = _bindCall(root.Element.prototype.addEventListener);
  4628. let stopper = e => _pause(e.target);
  4629. root.Audio = new Proxy(root.Audio, {
  4630. construct(audio, args) {
  4631. let res = _construct(audio, args);
  4632. _addEventListener(res, 'play', stopper, true);
  4633. return res;
  4634. }
  4635. });
  4636. let _tagName_get = _bindCall(Object.getOwnPropertyDescriptor(_Element, 'tagName').get);
  4637. root.Document.prototype.createElement = new Proxy(root.Document.prototype.createElement, {
  4638. apply(fun, that, args) {
  4639. let res = _apply(fun, that, args);
  4640. if (_tagName_get(res) === 'AUDIO')
  4641. _addEventListener(res, 'play', stopper, true);
  4642. return res;
  4643. }
  4644. });
  4645. });
  4646. }, deepWrapAPI),
  4647.  
  4648. 'spaces.ru': () => {
  4649. gardener('div:not(.f-c_fll) > a[href*="spaces.ru/?Cl="]', /./, {
  4650. parent: 'div'
  4651. });
  4652. gardener('.js-banner_rotator', /./, {
  4653. parent: '.widgets-group'
  4654. });
  4655. },
  4656.  
  4657. 'spam-club.blogspot.co.uk': () => {
  4658. let _clientHeight = Object.getOwnPropertyDescriptor(_Element, 'clientHeight'),
  4659. _clientWidth = Object.getOwnPropertyDescriptor(_Element, 'clientWidth');
  4660. let wrapGetter = (getter) => {
  4661. let _getter = getter;
  4662. return function () {
  4663. let _size = _getter.apply(this, arguments);
  4664. return _size ? _size : 1;
  4665. };
  4666. };
  4667. _clientHeight.get = wrapGetter(_clientHeight.get);
  4668. _clientWidth.get = wrapGetter(_clientWidth.get);
  4669. Object.defineProperty(_Element, 'clientHeight', _clientHeight);
  4670. Object.defineProperty(_Element, 'clientWidth', _clientWidth);
  4671. let _onload = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onload'),
  4672. _set_onload = _onload.set;
  4673. _onload.set = function () {
  4674. if (this instanceof HTMLImageElement)
  4675. return true;
  4676. _set_onload.apply(this, arguments);
  4677. };
  4678. Object.defineProperty(HTMLElement.prototype, 'onload', _onload);
  4679. },
  4680.  
  4681. 'sport-express.ru': () => gardener('.js-relap__item', />Реклама\s+<\//, {
  4682. root: '.container',
  4683. observe: true
  4684. }),
  4685.  
  4686. 'sports.ru': {
  4687. other: 'tribuna.com',
  4688. now() {
  4689. // extra functionality: shows/hides panel at the top depending on scroll direction
  4690. createStyle({
  4691. '.user-panel__fixed': {
  4692. transition: 'top 0.2s ease-in-out!important'
  4693. },
  4694. '.popup__overlay.feedback': {
  4695. display: 'none!important'
  4696. },
  4697. '.user-panel-up': {
  4698. top: '-40px!important'
  4699. },
  4700. '#branding-layout': {
  4701. margin_top: '100px!important'
  4702. }
  4703. }, {
  4704. id: 'fixes',
  4705. protect: false
  4706. });
  4707. scriptLander(() => {
  4708. yandexRavenStub();
  4709. webpackJsonpFilter(/AdBlockDetector|addBranding|loadPlista/);
  4710. }, nullTools, yandexRavenStub, webpackJsonpFilter);
  4711. },
  4712. dom() {
  4713. (function lookForPanel() {
  4714. let panel = _document.querySelector('.user-panel__fixed');
  4715. if (!panel)
  4716. setTimeout(lookForPanel, 100);
  4717. else
  4718. window.addEventListener(
  4719. 'wheel',
  4720. function (e) {
  4721. if (e.deltaY > 0 && !panel.classList.contains('user-panel-up'))
  4722. panel.classList.add('user-panel-up');
  4723. else if (e.deltaY < 0 && panel.classList.contains('user-panel-up'))
  4724. panel.classList.remove('user-panel-up');
  4725. }, false
  4726. );
  4727. })();
  4728. }
  4729. },
  4730.  
  4731. 'stealthz.ru': {
  4732. dom() {
  4733. // skip timeout
  4734. let $ = _document.querySelector.bind(_document);
  4735. let [timer_1, timer_2] = [$('#timer_1'), $('#timer_2')];
  4736. if (!timer_1 || !timer_2)
  4737. return;
  4738. timer_1.style.display = 'none';
  4739. timer_2.style.display = 'block';
  4740. }
  4741. },
  4742.  
  4743. 'tortuga.wtf': () => {
  4744. nt.define('Object.prototype.hideab', undefined);
  4745. },
  4746.  
  4747. 'tv.animebest.org': {
  4748. now() {
  4749. let _eval = win.eval;
  4750. win.eval = new win.Proxy(win.eval, {
  4751. apply(evl, ths, args) {
  4752. if (typeof args[0] === 'string' &&
  4753. args[0].includes("'VASTP'")) {
  4754. args[0] = args[0].replace("'VASTP'", "''");
  4755. win.eval = _eval;
  4756. }
  4757. return Reflect.apply(evl, ths, args);
  4758. }
  4759. });
  4760. }
  4761. },
  4762.  
  4763. 'tv-kanali.online': () => {
  4764. win.setTimeout = new Proxy(win.setTimeout, {
  4765. apply(fun, that, args) {
  4766. if (args[0].name && args[0].name.includes('doAd'))
  4767. return;
  4768. if (args[1] === 30000) args[1] = 100;
  4769. return _apply(fun, that, args);
  4770. }
  4771. });
  4772. },
  4773.  
  4774. 'video.khl.ru': () => {
  4775. let props = new Set(['detectBlockers', 'detectBlockersByLink', 'detectBlockersByElement']);
  4776. win.Object.defineProperty = new Proxy(win.Object.defineProperty, {
  4777. apply(def, that, args) {
  4778. if (props.has(args[1])) {
  4779. args[2] = {
  4780. key: args[1],
  4781. value() {
  4782. _console.log(`Skipped ${args[1]} call.`);
  4783. }
  4784. };
  4785. _console.log(`Replaced method ${args[1]}.`);
  4786. }
  4787. return Reflect.apply(def, that, args);
  4788. }
  4789. });
  4790. },
  4791.  
  4792. 'xatab-repack.net': {
  4793. other: 'rg-mechanics.org',
  4794. now() {
  4795. abortExecution.onSet('blocked');
  4796. }
  4797. },
  4798.  
  4799. 'xittv.net': () => scriptLander(() => {
  4800. let logNames = ['setup', 'trigger', 'on', 'off', 'onReady', 'onError', 'getConfig', 'addPlugin', 'getAdBlock'];
  4801. let skipEvents = ['adComplete', 'adSkipped', 'adBlock', 'adRequest', 'adMeta', 'adImpression', 'adError', 'adTime', 'adStarted', 'adClick'];
  4802. let _jwplayer;
  4803. Object.defineProperty(win, 'jwplayer', {
  4804. get() {
  4805. return _jwplayer;
  4806. },
  4807. set(x) {
  4808. _jwplayer = new Proxy(x, {
  4809. apply(fun, that, args) {
  4810. let res = fun.apply(that, args);
  4811. res = new Proxy(res, {
  4812. get(obj, name) {
  4813. if (logNames.includes(name) && typeof obj[name] === 'function')
  4814. return new Proxy(obj[name], {
  4815. apply(fun, that, args) {
  4816. if (name === 'setup') {
  4817. let o = args[0];
  4818. if (o)
  4819. delete o.advertising;
  4820. }
  4821. if (name === 'on' || name === 'trigger') {
  4822. let events = typeof args[0] === 'string' ? args[0].split(" ") : null;
  4823. if (events.length === 1 && skipEvents.includes(events[0]))
  4824. return res;
  4825. if (events.length > 1) {
  4826. let names = [];
  4827. for (let event of events)
  4828. if (!skipEvents.includes(event))
  4829. names.push(event);
  4830. if (names.length > 0)
  4831. args[0] = names.join(" ");
  4832. else
  4833. return res;
  4834. }
  4835. }
  4836. let subres = fun.apply(that, args);
  4837. _console.trace(`jwplayer().${name}(`, ...args, `) >>`, res);
  4838. return subres;
  4839. }
  4840. });
  4841. return obj[name];
  4842. }
  4843. });
  4844. return res;
  4845. }
  4846. });
  4847. _console.log('jwplayer =', x);
  4848. }
  4849. });
  4850. }),
  4851.  
  4852. 'yandex.tld': {
  4853. other: 'yandexsport.tld',
  4854. now: () => {
  4855. // Generic Yandex Scripts
  4856. const mainScript = () => {
  4857. let nt = new nullTools({
  4858. log: false,
  4859. trace: true
  4860. });
  4861.  
  4862. let cookiefilter = '';
  4863. // ads on afisha.yandex.ru, however it looks like selectiveEval isn't perfect
  4864. // since eval could be called in scope to access properties of that scope and
  4865. // such calls with it active break functionality on metrika.yandex.ru
  4866. if (/(^|\.)afisha\./.test(location.hostname)) {
  4867. selectiveEval(/AdvManagerStatic/);
  4868. nt.define('Object.prototype._adbStyles', null);
  4869. nt.define('Object.prototype._adbClass', null);
  4870. cookiefilter += (cookiefilter.length ? '|' : '') + 'checkcookie';
  4871. }
  4872.  
  4873. selectiveCookies(cookiefilter);
  4874. // remove banner on the start page
  4875. let AwapsJsonAPI_Json = function (...args) {
  4876. _console.log('>> new AwapsJsonAPI.Json(', ...args, ')');
  4877. };
  4878. const cleaner = (_params, nodes) => {
  4879. try {
  4880. for (let i = 0; i < nodes.length; i++)
  4881. nodes[i].parentNode.parentNode.removeChild(nodes[i].parentNode);
  4882. _console.log(`Removed banner placeholder.`);
  4883. } catch (ignore) {
  4884. _console.log(`Can't locate placeholder to remove.`);
  4885. }
  4886. };
  4887. Object.assign(AwapsJsonAPI_Json.prototype, {
  4888. checkBannerVisibility: nt.func(true, 'AwapsJsonAPI.Json.checkBannerVisibility'),
  4889. autorefresh: nt.proxy(cleaner, 'AwapsJsonAPI.Json.prototype.autorefresh'),
  4890. addIframeContent: nt.proxy(cleaner, 'AwapsJsonAPI.Json.prototype.addIframeContent'),
  4891. getHTML: nt.func('', 'AwapsJsonAPI.Json.getHTML')
  4892. });
  4893. AwapsJsonAPI_Json.prototype = nt.proxy(AwapsJsonAPI_Json.prototype, 'AwapsJsonAPI.Json.prototype');
  4894. AwapsJsonAPI_Json = nt.proxy(AwapsJsonAPI_Json);
  4895. if ('AwapsJsonAPI' in win) {
  4896. _console.log('Oops! AwapsJsonAPI already defined.');
  4897. let f = win.AwapsJsonAPI.Json;
  4898. win.AwapsJsonAPI.Json = AwapsJsonAPI_Json;
  4899. if (f && f.prototype)
  4900. f.prototype = AwapsJsonAPI_Json.prototype;
  4901. } else
  4902. nt.define('AwapsJsonAPI', nt.proxy({
  4903. Json: AwapsJsonAPI_Json
  4904. }));
  4905.  
  4906. let parseExport = x => {
  4907. if (!x)
  4908. return x;
  4909. // remove banner placeholder
  4910. if (x.banner && x.banner.cls && x.banner.cls.banner__parent) {
  4911. let hide = pattern => {
  4912. for (let banner of _document.querySelectorAll(pattern)) {
  4913. _setAttribute(banner, 'style', 'display:none!important');
  4914. _console.log('Hid banner placeholder.');
  4915. }
  4916. };
  4917. let _parent = `.${x.banner.cls.banner__parent}`;
  4918. hide(_parent);
  4919. _document.addEventListener('DOMContentLoaded', () => hide(_parent), false);
  4920. }
  4921.  
  4922. // remove banner data and some other stuff
  4923. delete x.banner;
  4924. delete x.consistency;
  4925. delete x['i-bannerid'];
  4926. delete x['i-counter'];
  4927. delete x['promo-curtain'];
  4928.  
  4929. // remove parts of ga-counter (complete removal break "ТВ Онлайн")
  4930. if (x['ga-counter'] && x['ga-counter'].data) {
  4931. x['ga-counter'].data.id = 0;
  4932. delete x['ga-counter'].data.ether;
  4933. delete x['ga-counter'].data.iframeSrc;
  4934. delete x['ga-counter'].data.iframeSrcEx;
  4935. }
  4936.  
  4937. // remove adblock detector parameters and clean up detector cookie
  4938. if ('adb' in x) {
  4939. let cookie = x.adb.data ? x.adb.data.cookie : undefined;
  4940. if (cookie) {
  4941. selectiveCookies(cookie);
  4942. x.adb.data.adb = 0;
  4943. }
  4944. delete x.adb;
  4945. }
  4946.  
  4947. return x;
  4948. };
  4949. // Yandex banner on main page and some other things
  4950. let _home = win.home,
  4951. _home_set = !!_home;
  4952. Object.defineProperty(win, 'home', {
  4953. get() {
  4954. return _home;
  4955. },
  4956. set(vl) {
  4957. if (!_home_set && vl === _home)
  4958. return;
  4959. _home_set = false;
  4960. _console.log('home =', vl);
  4961. let _home_export = parseExport(vl.export);
  4962. Object.defineProperty(vl, 'export', {
  4963. get() {
  4964. return _home_export;
  4965. },
  4966. set(vl) {
  4967. _home_export = parseExport(vl);
  4968. }
  4969. });
  4970. _home = vl;
  4971. }
  4972. });
  4973.  
  4974. // adblock circumvention on some Yandex domains
  4975. yandexRavenStub();
  4976.  
  4977. // news, sport, docviewer in emails and probably other places
  4978. abortExecution.onGet('yaads.adRenderedCount');
  4979. let AdvertPartner = nt.func(false, 'AdvertPartner');
  4980. nt.defineOn(AdvertPartner, 'defaultProps', {}, 'AdvertPartner.');
  4981. nt.defineOn(AdvertPartner, 'contextTypes', [], 'AdvertPartner.');
  4982. nt.define('Object.prototype.AdvertPartner', AdvertPartner);
  4983. // ads in videoplayer
  4984. nt.define('Object.prototype.useAbdBundle', false);
  4985.  
  4986. // code specific for /news and /sport
  4987. if (/^\/news(\/|$)/.test(location.pathname)) {
  4988. createStyle(
  4989. 'div[class]:not(.mg-grid__col) > .mg-grid__row > .mg-grid__col:last-child,' +
  4990. '.news-top-rubric-heading > span:only-child { display: none !important }'
  4991. );
  4992. gardener('.mg-grid__col > div[class*="_type_"]', /./, {
  4993. root: '.news-app__feed',
  4994. parent: '.mg-grid__col',
  4995. observe: true,
  4996. hide: true
  4997. });
  4998. }
  4999. if (/^\/sport(\/|$)/.test(location.pathname))
  5000. createStyle('.sport-advert_type_card { display: none !important }');
  5001.  
  5002. // abp detector cookie on yandex pogoda and afisha
  5003. win.Element.prototype.getAttribute = new Proxy(win.Element.prototype.getAttribute, {
  5004. apply(get, el, args) {
  5005. let res = _apply(get, el, args);
  5006. if (res && res.length > 20 && el instanceof HTMLBodyElement)
  5007. try {
  5008. let o = JSON.parse(res),
  5009. found = false,
  5010. check;
  5011. for (let prop in o) {
  5012. check = 'param' in o[prop] || 'aabCookieName' in o[prop];
  5013. if (check || 'banners' in o[prop]) {
  5014. found = true;
  5015. if (check)
  5016. selectiveCookies(o[prop].param || o[prop].aabCookieName);
  5017. _console.log(el.tagName, o, 'removed', o[prop]);
  5018. delete o[prop];
  5019. }
  5020. }
  5021. if (!found) _console.log(el.tagName, o);
  5022. res = JSON.stringify(o);
  5023. } catch (ignore) {}
  5024. return res;
  5025. }
  5026. });
  5027. };
  5028. scriptLander(mainScript, nullTools, yandexRavenStub, abortExecution, selectiveCookies, selectiveEval);
  5029.  
  5030. if ('attachShadow' in _Element) try {
  5031. let fakeRoot = () => ({
  5032. firstChild: null,
  5033. appendChild() {
  5034. return null;
  5035. },
  5036. querySelector() {
  5037. return null;
  5038. },
  5039. querySelectorAll() {
  5040. return null;
  5041. }
  5042. });
  5043. _Element.createShadowRoot = fakeRoot;
  5044. let shadows = new WeakMap();
  5045. let _attachShadow = Object.getOwnPropertyDescriptor(_Element, 'attachShadow');
  5046. _attachShadow.value = function () {
  5047. return shadows.set(this, fakeRoot()).get(this);
  5048. };
  5049. Object.defineProperty(_Element, 'attachShadow', _attachShadow);
  5050. let _shadowRoot = Object.getOwnPropertyDescriptor(_Element, 'shadowRoot');
  5051. _shadowRoot.set = () => null;
  5052. _shadowRoot.get = function () {
  5053. return shadows.has(this) ? shadows.get(this) : undefined;
  5054. };
  5055. Object.defineProperty(_Element, 'shadowRoot', _shadowRoot);
  5056. } catch (e) {
  5057. _console.warn('Unable to wrap Element.prototype.attachShadow\n', e);
  5058. }
  5059.  
  5060. // Disable banner styleSheet (on main page)
  5061. document.addEventListener('DOMContentLoaded', () => {
  5062. for (let sheet of document.styleSheets)
  5063. try {
  5064. for (let rule of sheet.cssRules)
  5065. if (rule.cssText.includes(' 728px 90px')) {
  5066. rule.parentStyleSheet.disabled = true;
  5067. _console.log('Disabled banner styleSheet:', rule.parentStyleSheet);
  5068. }
  5069. } catch (ignore) {}
  5070. }, false);
  5071.  
  5072. // Subdomain-specific Yandex scripts
  5073. const subDomain = location.hostname.slice(0, location.hostname.indexOf('.'));
  5074.  
  5075. // Yandex Mail ads
  5076. if (subDomain === 'mail') {
  5077. let wrap = vl => {
  5078. if (!vl)
  5079. return vl;
  5080. _console.log('Daria =', vl);
  5081. nt.defineOn(vl, 'AdBlock', nt.proxy({
  5082. detect: nt.func(new Promise(() => null), 'Daria.AdBlock.detect'),
  5083. enabled: false
  5084. }), 'Daria.');
  5085. nt.defineOn(vl, 'AdvPresenter', nt.proxy({
  5086. _config: nt.proxy({
  5087. banner: false,
  5088. done: false,
  5089. line: false
  5090. })
  5091. }), 'Daria.');
  5092. if (vl.Config) {
  5093. delete vl.Config.adBlockDetector;
  5094. delete vl.Config['adv-url'];
  5095. delete vl.Config.cryprox;
  5096. if (vl.Config.features) {
  5097. delete vl.Config.features.web_adloader_with_cookie_cache;
  5098. delete vl.Config.features.web_ads;
  5099. delete vl.Config.features.web_ads_mute;
  5100. }
  5101. vl.Config.mayHaveAdv = false;
  5102. }
  5103. return vl;
  5104. };
  5105. let _Daria = wrap(win.Daria);
  5106. if (_Daria)
  5107. _console.log('Wrapped already existing object "Daria".');
  5108. Object.defineProperty(win, 'Daria', {
  5109. get() {
  5110. return _Daria;
  5111. },
  5112. set(vl) {
  5113. if (vl === _Daria)
  5114. return;
  5115. _Daria = wrap(vl);
  5116. }
  5117. });
  5118. }
  5119.  
  5120. // Detector and ads on Yandex Music
  5121. if (subDomain === 'music') {
  5122. nt.define('tryPay', nt.func(null, 'tryPay'));
  5123. nt.define('Object.prototype.initMegabannerAPI', nt.func(null, 'initMegabannerAPI'));
  5124. nt.define('Object.prototype.mediaAd', undefined);
  5125. nt.define('Object.prototype.detect', () => new Promise(() => null));
  5126. nt.define('Object.prototype.loadContext', () => new Promise(r => r()));
  5127. nt.define('Object.prototype.antiAdbSetup', nt.func(null, 'ya.music.antiAdbSetup'));
  5128. }
  5129.  
  5130. const isSearch = /^\/(yand)?search[/?]/i.test(location.pathname);
  5131. if (['mail', 'music', 'tv', 'yandexsport'].includes(subDomain) || isSearch) {
  5132. // prevent/defuse adblock detector and cleanup localStorage
  5133. for (let name in localStorage)
  5134. if (name.startsWith('videoplayer-ad-session-') || ['ic', 'yu', 'ludca', 'test'].includes(name))
  5135. localStorage.removeItem(name);
  5136. nt.define('localStorage._mt__data', '');
  5137. nt.define('localStorage.yandexJSPlayerApiSavedSingleVideoSessionWatchedTimeSinceAd', Math.random() * 1000);
  5138.  
  5139. // cookie cleaner
  5140. let yp_keepCookieParts = /\.(sp|ygo|ygu)\./; // ygo = city id; ygu = detect city automatically
  5141. let _doc_proto = ('cookie' in _Document) ? _Document : Object.getPrototypeOf(_document);
  5142. let _cookie = Object.getOwnPropertyDescriptor(_doc_proto, 'cookie');
  5143. if (_cookie) {
  5144. let _set_cookie = _bindCall(_cookie.set);
  5145. _cookie.set = function (value) {
  5146. if (/^(mda=|yp=|ys=|yabs-|__|bltsr=)/.test(value))
  5147. // remove value, set expired
  5148. if (!value.startsWith('yp=')) {
  5149. value = value.replace(/^([^=]+=)[^;]+/, '$1').replace(/(expires=)[\w\s\d,]+/, '$1Thu, 01 Jan 1970 00');
  5150. _console.trace('expire cookie', value.match(/^[^=]+/)[0]);
  5151. } else {
  5152. let parts = value.split(';');
  5153. let values = parts[0].split('#').filter(part => yp_keepCookieParts.test(part));
  5154. if (values.length)
  5155. values[0] = values[0].replace(/^yp=/, '');
  5156. let res = `yp=${values.join('#')}`;
  5157. _console.trace(`set cookie ${res}, dropped ${parts[0].replace(res,'')}`);
  5158. parts[0] = res;
  5159. value = parts.join(';');
  5160. }
  5161. return _set_cookie(this, value);
  5162. };
  5163. Object.defineProperty(_doc_proto, 'cookie', _cookie);
  5164. }
  5165. }
  5166. },
  5167. dom: () => {
  5168. { // Partially based on https://greasyfork.org/en/scripts/22737-remove-yandex-redirect
  5169. let count = 0,
  5170. lock = false;
  5171. const log = () => {
  5172. count++;
  5173. if (lock)
  5174. return;
  5175. setTimeout(() => {
  5176. _console.log('Removed tracking attributes from', count, 'links.');
  5177. count = 0;
  5178. lock = false;
  5179. }, 3333);
  5180. lock = true;
  5181. };
  5182. const selectors = (
  5183. 'A[onmousedown*="/jsredir"],' +
  5184. 'A[data-log-node],' +
  5185. 'A[data-vdir-href],' +
  5186. 'A[data-counter]'
  5187. );
  5188. const removeTrackingAttributes = (link) => {
  5189. _removeAttribute(link, 'onmousedown');
  5190. _removeAttribute(link, 'data-log-node');
  5191. // data-vdir-href
  5192. _removeAttribute(link, 'data-vdir-href');
  5193. _removeAttribute(link, 'data-orig-href');
  5194. // data-counter
  5195. _removeAttribute(link, 'data-counter');
  5196. _removeAttribute(link, 'data-bem');
  5197. log();
  5198. };
  5199. const removeTracking = (scope) => {
  5200. if (scope instanceof Element)
  5201. for (let link of scope.querySelectorAll(selectors))
  5202. removeTrackingAttributes(link);
  5203. };
  5204.  
  5205. removeTracking(_document);
  5206. (new MutationObserver(
  5207. function (ms) {
  5208. let m, node;
  5209. for (m of ms)
  5210. for (node of m.addedNodes)
  5211. if (node instanceof HTMLAnchorElement && node.matches(selectors))
  5212. removeTrackingAttributes(node);
  5213. else
  5214. removeTracking(node);
  5215. }
  5216. )).observe(_de, {
  5217. childList: true,
  5218. subtree: true
  5219. });
  5220. }
  5221.  
  5222. // Subdomain-specific Yandex scripts
  5223. const subDomain = location.hostname.slice(0, location.hostname.indexOf('.'));
  5224.  
  5225. // Function to attach an observer to monitor dynamic changes on the page
  5226. const pageUpdateObserver = (func, obj, params) => {
  5227. if (obj)
  5228. (new MutationObserver(func))
  5229. .observe(obj, (params || {
  5230. childList: true,
  5231. subtree: true
  5232. }));
  5233. };
  5234. // Short name for parentNode.removeChild
  5235. const remove = node => {
  5236. if (!node || !node.parentNode)
  5237. return false;
  5238. _console.log('Removed node.');
  5239. node.parentNode.removeChild(node);
  5240. };
  5241. // Short name for setAttribute style to display:none
  5242. const hide = node => {
  5243. if (!node)
  5244. return false;
  5245. _console.log('Hid node.');
  5246. _setAttribute(node, 'style', 'display:none!important');
  5247. };
  5248.  
  5249. if (subDomain === 'music') {
  5250. const removeMusicAds = () => {
  5251. for (let node of _querySelectorAll('.ads-block'))
  5252. remove(node);
  5253. };
  5254. pageUpdateObserver(removeMusicAds, _querySelector('.sidebar'));
  5255. removeMusicAds();
  5256. }
  5257.  
  5258. if (subDomain === 'tv') {
  5259. const removeTVAds = () => {
  5260. const yadWord = /Яндекс.Директ/i;
  5261. for (let node of _querySelectorAll('div[class^="_"][data-reactid] > div'))
  5262. if (yadWord.test(node.textContent) || node.querySelector('iframe:not([src])')) {
  5263. if (node.offsetWidth) {
  5264. let pad = _document.createElement('div');
  5265. _setAttribute(pad, 'style', `width:${node.offsetWidth}px`);
  5266. node.parentNode.appendChild(pad);
  5267. }
  5268. remove(node);
  5269. }
  5270. };
  5271. pageUpdateObserver(removeTVAds, _document.body);
  5272. removeTVAds();
  5273. }
  5274.  
  5275. const isSearch = /^\/(yand)?search[/?]/i.test(location.pathname);
  5276. if (isSearch) {
  5277. const removeSearchAds = () => {
  5278. const adWords = /Реклама|Ad/i;
  5279. for (let node of _querySelectorAll('.serp-item'))
  5280. if (_getAttribute(node, 'role') === 'complementary' ||
  5281. adWords.test((node.querySelector('.label') || {}).textContent))
  5282. hide(node);
  5283. };
  5284. pageUpdateObserver(removeSearchAds, _querySelector('.main__content'));
  5285. removeSearchAds();
  5286. }
  5287.  
  5288. if (['mail', 'music', 'tv', 'yandexsport'].includes(subDomain) || isSearch) {
  5289. // Generic ads removal and fixes
  5290. for (let node of _querySelectorAll('.serp-header'))
  5291. node.style.marginTop = '0';
  5292. for (let node of _querySelectorAll(
  5293. '.serp-adv__head + .serp-item,' +
  5294. '#adbanner,' +
  5295. '.serp-adv,' +
  5296. '.b-spec-adv,' +
  5297. 'div[class*="serp-adv__"]:not(.serp-adv__found):not(.serp-adv__displayed)'
  5298. )) remove(node);
  5299. }
  5300. }
  5301. },
  5302.  
  5303. 'yap.ru': {
  5304. other: 'yaplakal.com',
  5305. now() {
  5306. gardener('form > table[id^="p_row_"]:nth-of-type(2)', /member1438|Administration/);
  5307. gardener('.icon-comments', /member1438|Administration|\/go\/\?http/, {
  5308. parent: 'tr',
  5309. siblings: -2
  5310. });
  5311. }
  5312. },
  5313.  
  5314. 'yapx.ru': () => scriptLander(() => {
  5315. selectiveCookies('adblock_state|adblock_views');
  5316. nt.define('blockAdBlock', {
  5317. on: nt.func(nt.proxy({}, 'blockAdBlock.on', nt.NULL), 'blockAdBlock.on'),
  5318. check: nt.func(null, 'blockAdBlock.check')
  5319. });
  5320. }, selectiveCookies, nullTools),
  5321.  
  5322. 'youtube.com': () => scriptLander(() => {
  5323. jsonFilter('playerResponse.adPlacements playerResponse.playerAds adPlacements playerAds');
  5324. }, jsonFilter),
  5325.  
  5326. 'znanija.com': () => scriptLander(() => {
  5327. localStorage.clear();
  5328. }, abortExecution)
  5329. };
  5330.  
  5331. // replace '.tld' in domain names, add alternative domain names if present and wrap functions into objects
  5332. {
  5333. const parts = _document.domain.split('.');
  5334. const tld = /\.tld$/;
  5335. const tldSubstitur = (() => {
  5336. // stores TLD of current domain (simplistic TLD implementation)
  5337. const last = parts.length - 1;
  5338. const tld = ['', parts[last]];
  5339. const secondLevel = [
  5340. 'biz', 'com', 'edu', 'gov', 'info', 'int', 'mil', 'net', 'org', 'pro'
  5341. ];
  5342. // add second from the end part of domain name as part of the TLD substitutor
  5343. // when domain name consists of more than 2 parts and it looks like a part of TLD
  5344. if ((parts[0] !== 'www' && parts.length > 2 || parts.length > 3) &&
  5345. (parts[last - 1].length < 3 || secondLevel.includes(parts[last - 1])))
  5346. tld.splice(0, 1, parts[last - 1]);
  5347. return tld.join('.');
  5348. })();
  5349. for (let name in scripts) {
  5350. if (typeof scripts[name] === 'function')
  5351. scripts[name] = {
  5352. now: scripts[name]
  5353. };
  5354. if (name.endsWith('.tld'))
  5355. scripts[name.replace(tld, tldSubstitur)] = scripts[name];
  5356. for (let domain of (scripts[name].other && scripts[name].other.split(/,\s*/) || [])) {
  5357. domain = domain.replace(tld, tldSubstitur);
  5358. if (domain in scripts)
  5359. _console.log('Error in scripts list. Script for', name, 'replaced script for', domain);
  5360. scripts[domain] = scripts[name];
  5361. }
  5362. delete scripts[name].other;
  5363. }
  5364. // scripts lookup
  5365. const windowEvents = ['load', 'unload', 'beforeunload'];
  5366. let domain;
  5367. while (parts.length > 1) {
  5368. domain = parts.join('.');
  5369. if (domain in scripts) {
  5370. for (let when in scripts[domain]) {
  5371. let script = scripts[domain][when];
  5372. if (when === 'now')
  5373. script();
  5374. else if (when === 'dom')
  5375. _document.addEventListener('DOMContentLoaded', script);
  5376. else if (windowEvents.includes(when))
  5377. win.addEventListener(when, scripts[domain][when]);
  5378. else
  5379. _document.addEventListener(when, scripts[domain][when]);
  5380. }
  5381. }
  5382. parts.shift();
  5383. }
  5384. }
  5385.  
  5386. // Batch script lander
  5387. if (!skipLander)
  5388. landScript(batchLand, batchPrepend);
  5389.  
  5390. { // JS Fixes Tools Menu
  5391. const incompatibleScriptHandler = !/^(Tamper|Violent)monkey$/.test(GM.info.scriptHandler) || GM.info.scriptHandler === 'Violentmonkey' && isFirefox;
  5392. // Debug function, lists all unusual window properties
  5393. const isNativeFunction = /^[^{]*\{[\s\r\n]*\[native\scode\][\s\r\n]*\}$/;
  5394. const getStrangeObjectsList = () => {
  5395. _console.group('Window strangers list');
  5396. const _skip = 'frames/self/window/webkitStorageInfo'.split('/');
  5397. for (let n of Object.getOwnPropertyNames(win))
  5398. try {
  5399. let val = win[n];
  5400. if (val && !_skip.includes(n) && (win !== window && val !== window[n] || win === window) &&
  5401. (typeof val !== 'function' || typeof val === 'function' && !isNativeFunction.test(_toString(val))))
  5402. _console.log(`${n} =`, val);
  5403. } catch (e) {
  5404. _console.log(n, 'returns error on read', e);
  5405. }
  5406. _console.groupEnd('Window strangers list');
  5407. };
  5408.  
  5409. const lines = {
  5410. linked: [],
  5411. MenuOptions: {
  5412. eng: 'Options',
  5413. rus: 'Настройки'
  5414. },
  5415. MenuCompatibilityWarning: {
  5416. eng: 'is not supported',
  5417. rus: 'не поддерживается'
  5418. },
  5419. langs: {
  5420. eng: 'English',
  5421. rus: 'Русский'
  5422. },
  5423. sObjBtn: {
  5424. eng: 'List unusual "window" properties in console',
  5425. rus: 'Вывести в консоль нестандартные свойства «window»'
  5426. },
  5427. HeaderTools: {
  5428. eng: 'Tools',
  5429. rus: 'Инструменты'
  5430. },
  5431. HeaderOptions: {
  5432. eng: 'Options',
  5433. rus: 'Настройки'
  5434. },
  5435. AccessStatisticsLabel: {
  5436. eng: 'Display stubs access statistics and JSON filter',
  5437. rus: 'Выводить статистику запросов к заглушкам и JSON фильтра'
  5438. },
  5439. AbortExecutionStatisticsLabel: {
  5440. eng: 'Display abort execution statistics',
  5441. rus: 'Выводить статистику прерывания исполнения скриптов'
  5442. },
  5443. LogAttachedCSSLabel: {
  5444. eng: 'Log CSS attached to a page',
  5445. rus: 'Журналировать CSS добавленные на страницу'
  5446. },
  5447. BlockNotificationPermissionRequestsLabel: {
  5448. eng: 'Block requests to Show Notifications on sites',
  5449. rus: 'Блокировать запросы Показывать Уведомления на сайтах'
  5450. },
  5451. ShowScriptHandlerCompatibilityWarningLabel: {
  5452. eng: 'Show compatibility warning in menu next to Options',
  5453. rus: 'Отображать предупреждение о совместимости в меню рядом с Настройками'
  5454. },
  5455. reg(el, name) {
  5456. this[name].link = el;
  5457. this.linked.push(name);
  5458. },
  5459. setLang(lang = 'eng') {
  5460. for (let name of this.linked) {
  5461. const el = this[name].link;
  5462. const label = this[name][lang];
  5463. el.textContent = label;
  5464. }
  5465. this.langs.link.value = lang;
  5466. jsf.Lang = lang;
  5467. }
  5468. };
  5469.  
  5470. const _createTextNode = _Document.createTextNode.bind(_document);
  5471. const createOptionsWindow = () => {
  5472. const root = _createElement('div'),
  5473. shadow = _attachShadow ? _attachShadow(root, {
  5474. mode: 'closed'
  5475. }) : root,
  5476. overlay = _createElement('div'),
  5477. inner = _createElement('div');
  5478.  
  5479. overlay.id = 'overlay';
  5480. overlay.appendChild(inner);
  5481. shadow.appendChild(overlay);
  5482.  
  5483. inner.id = 'inner';
  5484. inner.br = function appendBreakLine() {
  5485. return this.appendChild(_createElement('br'));
  5486. };
  5487.  
  5488. createStyle({
  5489. 'h2': {
  5490. margin_top: 0
  5491. },
  5492. 'h2, h3': {
  5493. margin_block_end: '0.5em'
  5494. },
  5495. 'div, button, select, input': {
  5496. font_family: 'Helvetica, Arial, sans-serif',
  5497. font_size: '12pt'
  5498. },
  5499. 'button': {
  5500. background: 'linear-gradient(to bottom, #f0f0f0 5%, #c0c0c0 100%)',
  5501. border_radius: '3px',
  5502. border: '1px solid #a1a1a1',
  5503. color: '#000000',
  5504. text_shadow: '0px 1px 0px #d4d4d4'
  5505. },
  5506. 'button:hover': {
  5507. background: 'linear-gradient(to bottom, #c0c0c0 5%, #f0f0f0 100%)'
  5508. },
  5509. 'button:active': {
  5510. position: 'relative',
  5511. top: '1px'
  5512. },
  5513. 'select': {
  5514. border: '1px solid darkgrey',
  5515. border_radius: '0px 0px 5px 5px',
  5516. border_top: '0px'
  5517. },
  5518. 'button:focus, select:focus': {
  5519. outline: 'none'
  5520. },
  5521. '#overlay': {
  5522. position: 'fixed',
  5523. top: 0,
  5524. left: 0,
  5525. bottom: 0,
  5526. right: 0,
  5527. background: 'rgba(0,0,0,0.65)',
  5528. z_index: 2147483647 // Highest z-index: Math.pow(2, 31) - 1
  5529. },
  5530. '#inner': {
  5531. background: 'whitesmoke',
  5532. color: 'black',
  5533. padding: '1.5em 1em 1.5em 1em',
  5534. max_width: '150ch',
  5535. position: 'absolute',
  5536. top: '50%',
  5537. left: '50%',
  5538. transform: 'translate(-50%, -50%)',
  5539. border: '1px solid darkgrey',
  5540. border_radius: '5px'
  5541. },
  5542. '#closeOptionsButton': {
  5543. float: 'right',
  5544. transform: 'translate(1em, -1.5em)',
  5545. border: 0,
  5546. border_radius: 0,
  5547. background: 'none',
  5548. box_shadow: 'none'
  5549. },
  5550. '#selectLang': {
  5551. float: 'right',
  5552. transform: 'translate(0, -1.5em)'
  5553. },
  5554. '.optionsLabel': {
  5555. padding_left: '1.5em',
  5556. text_indent: '-1em',
  5557. display: 'block'
  5558. },
  5559. '.optionsCheckbox': {
  5560. left: '-0.25em',
  5561. width: '1em',
  5562. height: '1em',
  5563. padding: 0,
  5564. margin: 0,
  5565. position: 'relative',
  5566. vertical_align: 'middle'
  5567. },
  5568. '@media (prefers-color-scheme: dark)': {
  5569. '#inner': {
  5570. background_color: '#292a2d',
  5571. color: 'white',
  5572. border: '1px solid #1a1b1e'
  5573. },
  5574. 'input': {
  5575. filter: 'invert(100%)'
  5576. },
  5577. 'button': {
  5578. background: 'linear-gradient(to bottom, #575757 5%, #303030 100%)',
  5579. border_color: '#575757',
  5580. color: '#f0f0f0',
  5581. text_shadow: '0px 1px 0px #171717'
  5582. },
  5583. 'button:hover': {
  5584. background: 'linear-gradient(to bottom, #303030 5%, #575757 100%)'
  5585. },
  5586. 'select': {
  5587. background_color: '#303030',
  5588. color: '#f0f0f0',
  5589. border: '1px solid #1a1b1e',
  5590. border_radius: '0px 0px 5px 5px',
  5591. border_top: '0px'
  5592. },
  5593. '#overlay': {
  5594. background: 'rgba(0,0,0,.85)',
  5595. }
  5596. }
  5597. }, {
  5598. root: shadow,
  5599. protect: false
  5600. });
  5601.  
  5602. // components
  5603. function createCheckbox(name) {
  5604. const checkbox = _createElement('input'),
  5605. label = _createElement('label');
  5606. checkbox.type = 'checkbox';
  5607. checkbox.classList.add('optionsCheckbox');
  5608. checkbox.checked = jsf[name];
  5609. checkbox.onclick = e => {
  5610. jsf[name] = e.target.checked;
  5611. return true;
  5612. };
  5613. label.classList.add('optionsLabel');
  5614. label.appendChild(checkbox);
  5615. const text = _createTextNode('');
  5616. label.appendChild(text);
  5617. Object.defineProperty(label, 'textContent', {
  5618. set(title) {
  5619. text.textContent = title;
  5620. }
  5621. });
  5622. return label;
  5623. }
  5624.  
  5625. // language & close
  5626. const closeBtn = _createElement('button');
  5627. closeBtn.onclick = () => _removeChild(root);
  5628. closeBtn.textContent = '\u2715';
  5629. closeBtn.id = 'closeOptionsButton';
  5630. inner.appendChild(closeBtn);
  5631.  
  5632. overlay.addEventListener('click', e => {
  5633. if (e.target === overlay) {
  5634. _removeChild(root);
  5635. e.preventDefault();
  5636. }
  5637. e.stopPropagation();
  5638. }, false);
  5639.  
  5640. const selectLang = _createElement('select');
  5641. for (let name in lines.langs) {
  5642. const langOption = _createElement('option');
  5643. langOption.value = name;
  5644. langOption.innerText = lines.langs[name];
  5645. selectLang.appendChild(langOption);
  5646. }
  5647. selectLang.id = 'selectLang';
  5648. lines.langs.link = selectLang;
  5649. inner.appendChild(selectLang);
  5650.  
  5651. selectLang.onchange = e => {
  5652. const lang = e.target.value;
  5653. lines.setLang(lang);
  5654. };
  5655.  
  5656. // fill options form
  5657. const header = _createElement('h2');
  5658. header.textContent = 'RU AdList JS Fixes';
  5659. inner.appendChild(header);
  5660.  
  5661. lines.reg(inner.appendChild(_createElement('h3')), 'HeaderTools');
  5662.  
  5663. const sObjBtn = _createElement('button');
  5664. sObjBtn.onclick = getStrangeObjectsList;
  5665. sObjBtn.textContent = '';
  5666. lines.reg(inner.appendChild(sObjBtn), 'sObjBtn');
  5667.  
  5668. lines.reg(inner.appendChild(_createElement('h3')), 'HeaderOptions');
  5669.  
  5670. lines.reg(inner.appendChild(createCheckbox('AccessStatistics')), 'AccessStatisticsLabel');
  5671. lines.reg(inner.appendChild(createCheckbox('AbortExecutionStatistics')), 'AbortExecutionStatisticsLabel');
  5672. lines.reg(inner.appendChild(createCheckbox('LogAttachedCSS')), 'LogAttachedCSSLabel');
  5673.  
  5674. inner.appendChild(_createElement('br'));
  5675. lines.reg(inner.appendChild(createCheckbox('BlockNotificationPermissionRequests')), 'BlockNotificationPermissionRequestsLabel');
  5676.  
  5677. if (incompatibleScriptHandler) {
  5678. inner.appendChild(_createElement('br'));
  5679. lines.reg(inner.appendChild(createCheckbox('ShowScriptHandlerCompatibilityWarning')), 'ShowScriptHandlerCompatibilityWarningLabel');
  5680. }
  5681.  
  5682. lines.setLang(jsf.Lang);
  5683.  
  5684. return root;
  5685. };
  5686.  
  5687. let optionsWindow;
  5688. GM_registerMenuCommand(lines.MenuOptions[jsf.Lang], () => _appendChild(optionsWindow = optionsWindow || createOptionsWindow()));
  5689. // add warning to script menu for non-Tampermonkey users
  5690. if (jsf.ShowScriptHandlerCompatibilityWarning && incompatibleScriptHandler)
  5691. GM_registerMenuCommand(`${GM.info.scriptHandler} ${lines.MenuCompatibilityWarning[jsf.Lang]}`, () => {
  5692. win.open(`https://greasyfork.org/${opts.Lang.slice(0,2)}/scripts/19993-ru-adlist-js-fixes#additional-info`);
  5693. });
  5694. }
  5695. })();