RU AdList JS Fixes

try to take over the world!

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

  1. // ==UserScript==
  2. // @name RU AdList JS Fixes
  3. // @namespace ruadlist_js_fixes
  4. // @version 20201102.6
  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|(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. const _DONE = _proto.DONE; // 4
  1565. const sendWrapper = {
  1566. apply(fun, that, args) {
  1567. if (xhrStopList.has(that)) {
  1568. if (that.readyState !== _DONE && xhrDispatchLoadList.has(that)) {
  1569. that.readyState = _DONE;
  1570. setTimeout(() => dispatchCustomEvent(that, 'load'), 0);
  1571. }
  1572. return null;
  1573. }
  1574. return _apply(fun, that, args);
  1575. }
  1576. };
  1577. ['send', 'setRequestHeader', 'getAllResponseHeaders'].forEach(
  1578. name => _proto[name] = new Proxy(_proto[name], sendWrapper)
  1579. );
  1580. // simulate readyState === 1 for blocked requests
  1581. const _readyState = Object.getOwnPropertyDescriptor(_proto, 'readyState');
  1582. _readyState.get = new Proxy(_readyState.get, {
  1583. apply(fun, that, args) {
  1584. return xhrStopList.has(that) ? 1 : _apply(fun, that, args);
  1585. }
  1586. });
  1587. Object.defineProperty(_proto, 'readyState', _readyState);
  1588. }
  1589.  
  1590. if (root.fetch)
  1591. root.fetch = new Proxy(root.fetch, {
  1592. apply(fun, that, args) {
  1593. let [url, opts] = args;
  1594. let method = opts && opts.method || 'GET';
  1595. if (typeof url === 'object' && 'headers' in url &&
  1596. 'url' in url && 'method' in url) // url instanceof Request
  1597. ({
  1598. url,
  1599. method
  1600. } = url);
  1601. if (checkRequest('fetch', method, url))
  1602. return new Promise(() => null);
  1603. return _apply(fun, that, args);
  1604. }
  1605. });
  1606.  
  1607. const _script_src = Object.getOwnPropertyDescriptor(root.HTMLScriptElement.prototype, 'src');
  1608. _script_src.set = new Proxy(_script_src.set, {
  1609. apply(fun, that, args) {
  1610. if (fabPatterns.test(args[0])) {
  1611. _console.trace('Blocked set script.src request:', args[0]);
  1612. deployFABStub(root);
  1613. setTimeout(() => dispatchCustomEvent(that, 'load'), 0);
  1614. return;
  1615. }
  1616. return checkRequest('set', 'script.src', args[0]) || _apply(fun, that, args);
  1617. }
  1618. });
  1619. Object.defineProperty(root.HTMLScriptElement.prototype, 'src', _script_src);
  1620.  
  1621. const adregain_pattern = /ggg==" alt="advertisement"/;
  1622. if (root.self !== root.top) // in IFrame
  1623. root.document.write = new Proxy(root.document.write, {
  1624. apply(fun, that, args) {
  1625. if (adregain_pattern.test(args[0])) {
  1626. _console.log('Skipped AdRegain frame.');
  1627. args[0] = '';
  1628. }
  1629. return _apply(fun, that, args);
  1630. }
  1631. });
  1632. });
  1633. }, deepWrapAPI
  1634. );
  1635.  
  1636. // === Helper functions ===
  1637.  
  1638. // function to search and remove nodes by content
  1639. // selector - standard CSS selector to define set of nodes to check
  1640. // words - regular expression to check content of the suspicious nodes
  1641. // params - object with multiple extra parameters:
  1642. // .log - display log in the console
  1643. // .hide - set display to none instead of removing from the page
  1644. // .parent - parent node to remove if content is found in the child node
  1645. // .siblings - number of simling nodes to remove (excluding text nodes)
  1646. function scissors(selector, words, scope, params) {
  1647. const logger = (...args) => {
  1648. if (params.log) _console.log(...args);
  1649. };
  1650. const scHide = node => {
  1651. let style = _getAttribute(node, 'style') || '',
  1652. hide = ';display:none!important;';
  1653. if (style.indexOf(hide) < 0)
  1654. _setAttribute(node, 'style', style + hide);
  1655. };
  1656.  
  1657. if (!scope.contains(_document.body))
  1658. logger('[s] scope', scope);
  1659. let remFunc = (params.hide ? scHide : node => node.parentNode.removeChild(node)),
  1660. iterFunc = (params.siblings > 0 ? 'nextElementSibling' : 'previousElementSibling'),
  1661. toRemove = [],
  1662. siblings;
  1663. for (let node of scope.querySelectorAll(selector)) {
  1664. // drill up to a parent node if specified, break if not found
  1665. if (params.parent) {
  1666. let old = node;
  1667. node = node.closest(params.parent);
  1668. if (node === null || node.contains(scope)) {
  1669. logger('[s] went out of scope with', old);
  1670. continue;
  1671. }
  1672. }
  1673. logger('[s] processing', node);
  1674. if (toRemove.includes(node))
  1675. continue;
  1676. if (words.test(node.innerHTML)) {
  1677. // skip node if already marked for removal
  1678. logger('[s] marked for removal');
  1679. toRemove.push(node);
  1680. // add multiple nodes if defined more than one sibling
  1681. siblings = Math.abs(params.siblings) || 0;
  1682. while (siblings) {
  1683. node = node[iterFunc];
  1684. if (!node) break; // can't go any further - exit
  1685. logger('[s] adding sibling node', node);
  1686. toRemove.push(node);
  1687. siblings -= 1;
  1688. }
  1689. }
  1690. }
  1691. const toSkip = [];
  1692. toSkip.checkNode = node => !toRemove.every(other => other === node || !node.contains(other));
  1693. for (let node of toRemove)
  1694. if (toSkip.checkNode(node))
  1695. toSkip.push(node);
  1696. if (toRemove.length)
  1697. logger(`[s] proceeding with ${params.hide?'hide':'removal'} of`, toRemove, `skip`, toSkip);
  1698. for (let node of toRemove)
  1699. if (!toSkip.includes(node))
  1700. remFunc(node);
  1701. }
  1702.  
  1703. // function to perform multiple checks if ads inserted with a delay
  1704. // by default does 30 checks withing a 3 seconds unless nonstop mode specified
  1705. // also does 1 extra check when a page completely loads
  1706. // selector and words - passed dow to scissors
  1707. // params - object with multiple extra parameters:
  1708. // .log - display log in the console
  1709. // .root - selector to narrow down scope to scan;
  1710. // .observe - if true then check will be performed continuously;
  1711. // Other parameters passed down to scissors.
  1712. function gardener(selector, words, params) {
  1713. let logger = (...args) => {
  1714. if (params.log) _console.log(...args);
  1715. };
  1716. params = params || {};
  1717. logger(`[gardener] selector: '${selector}' detector: ${words} options: ${JSON.stringify(params)}`);
  1718. let scope;
  1719. let globalScope = [_de];
  1720. let domLoaded = false;
  1721. let getScope = root => root ? _de.querySelectorAll(root) : globalScope;
  1722. let onevent = e => {
  1723. logger(`[gardener] cleanup on ${Object.getPrototypeOf(e)} "${e.type}"`);
  1724. for (let node of scope)
  1725. scissors(selector, words, node, params);
  1726. };
  1727. let repeater = n => {
  1728. if (!domLoaded && n) {
  1729. setTimeout(repeater, 500, n - 1);
  1730. scope = getScope(params.root);
  1731. if (!scope) // exit if the root element is not present on the page
  1732. return 0;
  1733. onevent({
  1734. type: 'Repeater'
  1735. });
  1736. }
  1737. };
  1738. repeater(20);
  1739. _document.addEventListener(
  1740. 'DOMContentLoaded', (e) => {
  1741. domLoaded = true;
  1742. // narrow down scope to a specific element
  1743. scope = getScope(params.root);
  1744. if (!scope) // exit if the root element is not present on the page
  1745. return 0;
  1746. logger('[g] scope', scope);
  1747. // add observe mode if required
  1748. if (params.observe) {
  1749. let params = {
  1750. childList: true,
  1751. subtree: true
  1752. };
  1753. let observer = new MutationObserver(
  1754. function (ms) {
  1755. for (let m of ms)
  1756. if (m.addedNodes.length)
  1757. onevent(m);
  1758. }
  1759. );
  1760. for (let node of scope)
  1761. observer.observe(node, params);
  1762. logger('[g] observer enabled');
  1763. }
  1764. onevent(e);
  1765. }, false);
  1766. // wait for a full page load to do one extra cut
  1767. win.addEventListener('load', onevent, false);
  1768. }
  1769.  
  1770. // wrap popular methods to open a new tab to catch specific behaviours
  1771. function createWindowOpenWrapper(openFunc) {
  1772. const parser = _createElement('a');
  1773. const openWhitelist = (url, parent) => {
  1774. parser.href = url;
  1775. return parser.hostname === 'www.imdb.com' || parser.hostname === 'www.kinopoisk.ru' ||
  1776. parent.hostname === 'radikal.ru' && url === undefined;
  1777. };
  1778.  
  1779. function redefineOpen(root) {
  1780. if ('open' in root)
  1781. root.open = new Proxy(root.open, {
  1782. apply(fun, that, args) {
  1783. if (openWhitelist(args[0], location)) {
  1784. _console.log('Whitelisted popup:', ...args);
  1785. return _apply(fun, that, args);
  1786. }
  1787. return openFunc(...args);
  1788. }
  1789. });
  1790. }
  1791. redefineOpen(win);
  1792.  
  1793. const createElementWrapper = {
  1794. apply(fun, that, args) {
  1795. const el = _apply(fun, that, args);
  1796. // redefine window.open in first-party frames
  1797. if (el instanceof HTMLIFrameElement || el instanceof HTMLObjectElement)
  1798. el.addEventListener('load', (e) => {
  1799. try {
  1800. redefineOpen(e.target.contentWindow);
  1801. } catch (ignore) {}
  1802. }, false);
  1803. return el;
  1804. }
  1805. };
  1806.  
  1807. function redefineCreateElement(obj) {
  1808. for (let root of [obj.document, _Document])
  1809. if ('createElement' in root) {
  1810. root.createElement = new Proxy(root.createElement, createElementWrapper);
  1811. nt.defineOn(root, 'createElement', new Proxy(createElement, {}), 'Document.prototype.');
  1812. }
  1813. }
  1814. redefineCreateElement(win);
  1815.  
  1816. // wrap window.open in newly added first-party frames
  1817. const wrappedAppendChild = new Proxy(_Node.appendChild, {
  1818. apply(fun, that, args) {
  1819. let el = _apply(fun, that, args);
  1820. if (el instanceof HTMLIFrameElement)
  1821. try {
  1822. redefineOpen(el.contentWindow);
  1823. redefineCreateElement(el.contentWindow);
  1824. } catch (ignore) {}
  1825. return el;
  1826. }
  1827. });
  1828. // ABP Freeze Element snippet replaces normal properties with getters without setters
  1829. const _Node_appendChild = Object.getOwnPropertyDescriptor(Node.prototype, 'appendChild');
  1830. if (_Node_appendChild.configurable) {
  1831. if (_Node_appendChild.value)
  1832. _Node_appendChild.value = wrappedAppendChild;
  1833. if (_Node_appendChild.get)
  1834. _Node_appendChild.get = () => wrappedAppendChild;
  1835. Object.defineProperty(_Node, 'appendChild', _Node_appendChild);
  1836. }
  1837. }
  1838.  
  1839. // Function to catch and block various methods to open a new window with 3rd-party content.
  1840. // Some advertisement networks went way past simple window.open call to circumvent default popup protection.
  1841. // This funciton blocks window.open, ability to restore original window.open from an IFRAME object,
  1842. // ability to perform an untrusted (not initiated by user) click on a link, click on a link without a parent
  1843. // node or simply a link with piece of javascript code in the HREF attribute.
  1844. function preventPopups() {
  1845. // call sandbox-me if in iframe and not whitelisted
  1846. if (inIFrame) {
  1847. win.top.postMessage({
  1848. name: 'sandbox-me',
  1849. href: win.location.href
  1850. }, '*');
  1851. return;
  1852. }
  1853.  
  1854. scriptLander(() => {
  1855. let open = (...args) => {
  1856. '[native code]';
  1857. _console.trace('Site attempted to open a new window', ...args);
  1858. return {
  1859. document: nt.proxy({
  1860. write: nt.func({}, 'write'),
  1861. writeln: nt.func({}, 'writeln')
  1862. }),
  1863. location: nt.proxy({})
  1864. };
  1865. };
  1866.  
  1867. createWindowOpenWrapper(open);
  1868.  
  1869. _console.log('Popup prevention enabled.');
  1870. }, nullTools, createWindowOpenWrapper);
  1871. }
  1872.  
  1873. // Helper function to close background tab if site opens itself in a new tab and then
  1874. // loads a 3rd-party page in the background one (thus performing background redirect).
  1875. function preventPopunders() {
  1876. // create "close_me" event to call high-level window.close()
  1877. let eventName = `close_me_${Math.random().toString(36).substr(2)}`;
  1878. let callClose = () => {
  1879. _console.log('close call');
  1880. window.close();
  1881. };
  1882. window.addEventListener(eventName, callClose, true);
  1883.  
  1884. scriptLander(() => {
  1885. // get host of a provided URL with help of an anchor object
  1886. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  1887. let parseURL = _document.createElement('A');
  1888. let getHost = url => {
  1889. parseURL.href = url;
  1890. return parseURL.hostname;
  1891. };
  1892. // site went to a new tab and attempts to unload
  1893. // call for high-level close through event
  1894. let closeWindow = () => window.dispatchEvent(new CustomEvent(eventName, {}));
  1895. // check is URL local or goes to different site
  1896. let isLocal = (url) => {
  1897. if (url === location.pathname || url === location.href)
  1898. return true; // URL points to current pathname or full address
  1899. let host = getHost(url);
  1900. let site = location.hostname;
  1901. return host !== '' && // URLs with unusual protocol may have empty 'host'
  1902. (site === host || site.endsWith(`.${host}`) || host.endsWith(`.${site}`));
  1903. };
  1904.  
  1905. let _open = window.open.bind(window);
  1906. let open = (...args) => {
  1907. '[native code]';
  1908. let url = args[0];
  1909. if (url && isLocal(url))
  1910. window.addEventListener('beforeunload', closeWindow, true);
  1911. return _open(...args);
  1912. };
  1913.  
  1914. createWindowOpenWrapper(open);
  1915.  
  1916. _console.log("Background redirect prevention enabled.");
  1917. }, `let eventName="${eventName}"`, nullTools, createWindowOpenWrapper);
  1918. }
  1919.  
  1920. // Mix between check for popups and popunders
  1921. // Significantly more agressive than both and can't be used as universal solution
  1922. function preventPopMix() {
  1923. if (inIFrame) {
  1924. win.top.postMessage({
  1925. name: 'sandbox-me',
  1926. href: win.location.href
  1927. }, '*');
  1928. return;
  1929. }
  1930.  
  1931. // create "close_me" event to call high-level window.close()
  1932. let eventName = `close_me_${Math.random().toString(36).substr(2)}`;
  1933. let callClose = () => {
  1934. _console.log('close call');
  1935. window.close();
  1936. };
  1937. window.addEventListener(eventName, callClose, true);
  1938.  
  1939. scriptLander(() => {
  1940. let _open = window.open,
  1941. parseURL = _document.createElement('A');
  1942. // get host of a provided URL with help of an anchor object
  1943. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  1944. let getHost = (url) => {
  1945. parseURL.href = url;
  1946. return parseURL.host;
  1947. };
  1948. // site went to a new tab and attempts to unload
  1949. // call for high-level close through event
  1950. let closeWindow = () => {
  1951. _open(window.location, '_self');
  1952. window.dispatchEvent(new CustomEvent(eventName, {}));
  1953. };
  1954. // check is URL local or goes to different site
  1955. function isLocal(url) {
  1956. let loc = window.location;
  1957. if (url === loc.pathname || url === loc.href)
  1958. return true; // URL points to current pathname or full address
  1959. let host = getHost(url),
  1960. site = loc.host;
  1961. if (host === '')
  1962. return false; // URLs with unusual protocol may have empty 'host'
  1963. if (host.length > site.length)
  1964. [site, host] = [host, site];
  1965. return site.includes(host, site.length - host.length);
  1966. }
  1967.  
  1968. // add check for redirect for 5 seconds, then disable it
  1969. function checkRedirect() {
  1970. window.addEventListener('beforeunload', closeWindow, true);
  1971. setTimeout(closeWindow => window.removeEventListener('beforeunload', closeWindow, true), 5000, closeWindow);
  1972. }
  1973.  
  1974. function open(url, name) {
  1975. '[native code]';
  1976. if (url && isLocal(url) && (!name || name === '_blank')) {
  1977. _console.trace('Suspicious local new window', ...arguments);
  1978. checkRedirect();
  1979. /* jshint validthis: true */
  1980. return _open.apply(this, arguments);
  1981. }
  1982. _console.trace('Blocked attempt to open a new window', ...arguments);
  1983. return {
  1984. document: {
  1985. write() {},
  1986. writeln() {}
  1987. }
  1988. };
  1989. }
  1990.  
  1991. function clickHandler(e) {
  1992. let link = e.target,
  1993. url = link.href || '';
  1994. if (e.targetParentNode && e.isTrusted || link.target !== '_blank') {
  1995. _console.log('Link', link, 'were created dinamically, but looks fine.');
  1996. return true;
  1997. }
  1998. if (isLocal(url) && link.target === '_blank') {
  1999. _console.log('Suspicious local link', link);
  2000. checkRedirect();
  2001. return;
  2002. }
  2003. _console.log('Blocked suspicious click on a link', link);
  2004. e.stopPropagation();
  2005. e.preventDefault();
  2006. }
  2007.  
  2008. createWindowOpenWrapper(open, clickHandler);
  2009.  
  2010. _console.log("Mixed popups prevention enabled.");
  2011. }, `let eventName="${eventName}"`, createWindowOpenWrapper);
  2012. }
  2013. // External listener for case when site known to open popups were loaded in iframe
  2014. // It will sandbox any iframe which will send message 'forbid.popups' (preventPopups sends it)
  2015. // Some sites replace frame's window.location with data-url to run in clean context
  2016. if (!inIFrame) window.addEventListener(
  2017. 'message',
  2018. function (e) {
  2019. if (!e.data || e.data.name !== 'sandbox-me' || !e.data.href)
  2020. return;
  2021. let src = e.data.href;
  2022. for (let frame of _document.querySelectorAll('iframe'))
  2023. if (frame.contentWindow === e.source) {
  2024. if (frame.hasAttribute('sandbox')) {
  2025. if (!frame.sandbox.contains('allow-popups'))
  2026. return; // exit frame since it's already sandboxed and popups are blocked
  2027. // remove allow-popups if frame already sandboxed
  2028. frame.sandbox.remove('allow-popups');
  2029. } else
  2030. // set sandbox mode for troublesome frame and allow scripts, forms and a few other actions
  2031. // technically allowing both scripts and same-origin allows removal of the sandbox attribute,
  2032. // but to apply content must be reloaded and this script will re-apply it in the result
  2033. frame.setAttribute('sandbox', 'allow-forms allow-scripts allow-presentation allow-top-navigation allow-same-origin');
  2034. _console.log('Disallowed popups from iframe', frame);
  2035.  
  2036. // reload frame content to apply restrictions
  2037. if (!src) {
  2038. src = frame.src;
  2039. _console.log('Unable to get current iframe location, reloading from src', src);
  2040. } else
  2041. _console.log('Reloading iframe with URL', src);
  2042. frame.src = 'about:blank';
  2043. frame.src = src;
  2044. }
  2045. }, false
  2046. );
  2047.  
  2048. const evalPatternYandex = /{exports:{},id:r,loaded:!1}|containerId:(.|\r|\n)+params:/,
  2049. evalPatternGeneric = /_0x|location\s*?=|location.href\s*?=|location.assign\(|open\(/i;
  2050.  
  2051. function selectiveEval(...patterns) {
  2052. let fullLog = false;
  2053. if (patterns[patterns.length - 1] === true) {
  2054. fullLog = true;
  2055. patterns.length = patterns.length - 1;
  2056. }
  2057. if (patterns.length === 0)
  2058. patterns.push(evalPatternGeneric);
  2059. win.eval = new Proxy(win.eval, {
  2060. apply(fun, that, args) {
  2061. if (patterns.some(pattern => pattern.test(args[0]))) {
  2062. _console[fullLog ? 'trace' : 'log'](`Skipped eval ${fullLog ? args[0] : args[0].slice(0, 512)}${fullLog ? '' : '\u2026'}`);
  2063. return null;
  2064. }
  2065. try {
  2066. if (fullLog)
  2067. _console.trace(`eval ${args[0]}`);
  2068. return _apply(fun, that, args);
  2069. } catch (e) {
  2070. _console.error('Crash source:', args[0]);
  2071. throw e;
  2072. }
  2073. }
  2074. });
  2075. }
  2076. selectiveEval.toString = new Proxy(selectiveEval.toString, {
  2077. apply(...args) {
  2078. return `${_apply(...args)} const evalPatternYandex = ${evalPatternYandex}, evalPatternGeneric = ${evalPatternGeneric}`;
  2079. }
  2080. });
  2081.  
  2082. // hides cookies by pattern and attempts to remove them if they already set
  2083. // also prevents setting new versions of such cookies
  2084. function selectiveCookies(scPattern = '', opts = {}) {
  2085. let patterns = scPattern.split('|');
  2086. if (patterns[0] !== '~default') {
  2087. // Google Analytics cookies
  2088. patterns.push('_g(at?|id)|__utm[a-z]');
  2089. // Yandex ABP detection cookies
  2090. patterns.push('bltsr|blcrm');
  2091. } else
  2092. patterns.shift();
  2093. let blacklist = new RegExp(`(^|;\\s?)(${patterns.join('|')})($|=)`);
  2094.  
  2095. const root = opts.root || win;
  2096. const _root_Document = Object.getPrototypeOf(root.HTMLDocument.prototype);
  2097. const _doc_proto = ('cookie' in _root_Document) ? _root_Document : Object.getPrototypeOf(root.document);
  2098. const _cookie = Object.getOwnPropertyDescriptor(_doc_proto, 'cookie');
  2099. const _set_cookie = _bindCall(_cookie.set);
  2100.  
  2101. let removed = new Set();
  2102. const removeLog = (cookie) => {
  2103. let strings = [`${cookie.name}=${cookie.value}`];
  2104. if (cookie.domain)
  2105. strings.push(`domain=${cookie.domain}`);
  2106. if (cookie.path)
  2107. strings.push(`path=${cookie.path}`);
  2108. if (cookie.sameSite !== 'unspecified')
  2109. strings.push(`sameSite=${cookie.sameSite}`);
  2110. for (let name of ['httpOnly', 'hostOnly', 'secure', 'session'])
  2111. if (cookie[name]) strings.push(name);
  2112. let full = strings.join('; ');
  2113. if (!removed.has(full))
  2114. _console.log(`Removed cookie: ${full}`);
  2115. removed.add(full);
  2116. };
  2117.  
  2118. let skipTM = true;
  2119. const asyncCookieCleaner = () => {
  2120. GM.cookie.list({
  2121. url: location.href
  2122. }).then(cookies => {
  2123. if (!cookies) return;
  2124. if (skipTM) {
  2125. cookies = cookies.filter(x => !x.name.startsWith('TM_'));
  2126. skipTM = false;
  2127. }
  2128. for (let cookie of cookies)
  2129. if (blacklist.test(cookie.name)) {
  2130. if (skipTM && cookie.name)
  2131. continue;
  2132. GM.cookie.delete(cookie);
  2133. removeLog(cookie);
  2134. }
  2135. }, () => null);
  2136. };
  2137.  
  2138. const useOldPass = (() => {
  2139. // returns true if GM version <= 4.10
  2140. let v = GM.info.version.split('.').map(x => x - 0);
  2141. return v[0] < 4 || v[0] === 4 && v[1] <= 10 && v[2] === undefined || GM.info.scriptHandler !== 'Tampermonkey';
  2142. })();
  2143.  
  2144. const getName = (cookie) => cookie && cookie.indexOf('=') ? /^(.+?)=/.exec(cookie)[1] : cookie;
  2145.  
  2146. const removeCookie = (cookie, that) => {
  2147. const expireCookie = (name, domain) => {
  2148. domain = domain ? `;domain=${domain.join('.')}` : '';
  2149. _set_cookie(that, `${name}=;Max-Age=0;path=/${domain}`);
  2150. _set_cookie(that, `${name}=;Max-Age=0;path=/${domain.replace('=', '=.')}`);
  2151. };
  2152. const name = getName(cookie);
  2153. const domain = that.location.hostname.split('.');
  2154.  
  2155. expireCookie(name);
  2156. while (domain.length > 1) {
  2157. try {
  2158. expireCookie(name, domain);
  2159. } catch (e) {
  2160. _console.error(e);
  2161. }
  2162. domain.shift();
  2163. }
  2164. _console.log('Removing existing cookie:', cookie);
  2165. };
  2166.  
  2167. if (_cookie) {
  2168. // skip setting unwanted cookies
  2169. _cookie.set = new Proxy(_cookie.set, {
  2170. apply(fun, that, args) {
  2171. if (useOldPass) {
  2172. let cookie = args[0];
  2173. if (blacklist.test(getName(cookie))) {
  2174. _console.log('Ignored cookie: %s', cookie);
  2175. removeCookie(cookie, that);
  2176. return;
  2177. }
  2178. }
  2179. _apply(fun, that, args);
  2180. asyncCookieCleaner();
  2181. return true;
  2182. }
  2183. });
  2184. // hide unwanted cookies from site
  2185. _cookie.get = new Proxy(_cookie.get, {
  2186. apply(fun, that, args) {
  2187. asyncCookieCleaner();
  2188. let res = _apply(fun, that, args);
  2189. if (blacklist.test(res)) {
  2190. let stack = [];
  2191. for (let cookie of res.split(/;\s?/))
  2192. if (!blacklist.test(getName(cookie)))
  2193. stack.push(cookie);
  2194. else if (useOldPass) removeCookie(cookie, that);
  2195. res = stack.join('; ');
  2196. }
  2197. return res;
  2198. }
  2199. });
  2200. Object.defineProperty(_doc_proto, 'cookie', _cookie);
  2201. _console.log('Active cookies:', root.document.cookie);
  2202. }
  2203. }
  2204.  
  2205. // Locates a node with specific text in Russian
  2206. // Uses table of substitutions for similar letters
  2207. let selectNodeByTextContent = (() => {
  2208. let subs = {
  2209. // english & greek
  2210. 'А': 'AΑ',
  2211. 'В': 'BΒ',
  2212. 'Г': 'Γ',
  2213. 'Е': 'EΕ',
  2214. 'З': '3',
  2215. 'К': 'KΚ',
  2216. 'М': 'MΜ',
  2217. 'Н': 'HΗ',
  2218. 'О': 'OΟ',
  2219. 'П': 'Π',
  2220. 'Р': 'PΡ',
  2221. 'С': 'C',
  2222. 'Т': 'T',
  2223. 'Ф': 'Φ',
  2224. 'Х': 'XΧ'
  2225. };
  2226. let regExpBuilder = text => new RegExp(
  2227. text.toUpperCase()
  2228. .split('')
  2229. .map(function (e) {
  2230. return `${e in subs ? `[${e}${subs[e]}]` : (e === ' ' ? '\\s+' : e)}[\u200b\u200c\u200d]*`;
  2231. })
  2232. .join(''),
  2233. 'i');
  2234. let reMap = {};
  2235. return (re, opts = {
  2236. root: _document.body
  2237. }) => {
  2238. if (!re.test) {
  2239. if (!reMap[re])
  2240. reMap[re] = regExpBuilder(re);
  2241. re = reMap[re];
  2242. }
  2243.  
  2244. for (let child of opts.root.children)
  2245. if (re.test(child.textContent)) {
  2246. if (opts.shallow)
  2247. return child;
  2248. opts.root = child;
  2249. return selectNodeByTextContent(re, opts) || child;
  2250. }
  2251. };
  2252. })();
  2253.  
  2254. // webpackJsonp filter
  2255. function webpackJsonpFilter(blacklist, log = false) {
  2256. function wrapPush(webpack) {
  2257. let _push = webpack.push.bind(webpack);
  2258. Object.defineProperty(webpack, 'push', {
  2259. get() {
  2260. return _push;
  2261. },
  2262. set(vl) {
  2263. _push = new Proxy(vl, {
  2264. apply(fun, that, args) {
  2265. wrapper: {
  2266. if (!(args[0] instanceof Array))
  2267. break wrapper;
  2268. let mainName;
  2269. if (args[0][2] instanceof Array && args[0][2][0] instanceof Array)
  2270. mainName = args[0][2][0][0];
  2271. let funs = args[0][1];
  2272. if (!(funs instanceof Object && !(funs instanceof Array)))
  2273. break wrapper;
  2274. const noopFunc = (name, text) => () => _console.log(`Skip webpack ${name}`, text);
  2275. for (let name in funs) {
  2276. if (typeof funs[name] !== 'function')
  2277. continue;
  2278. if (blacklist.test(_toString(funs[name])) && name !== mainName)
  2279. funs[name] = noopFunc(name, log ? _toString(funs[name]) : '');
  2280. }
  2281. }
  2282. _console.log('webpack.push()');
  2283. return _apply(fun, that, args);
  2284. }
  2285. });
  2286. return true;
  2287. }
  2288. });
  2289. return webpack;
  2290. }
  2291. let _webpackJsonp = wrapPush([]);
  2292. Object.defineProperty(win, 'webpackJsonp', {
  2293. get() {
  2294. return _webpackJsonp;
  2295. },
  2296. set(vl) {
  2297. if (vl === _webpackJsonp)
  2298. return;
  2299. _console.log('new webpackJsonp', vl);
  2300. _webpackJsonp = wrapPush(vl);
  2301. }
  2302. });
  2303. }
  2304.  
  2305. // JSON filter
  2306. // removeList - list of paths divided by space to remove
  2307. // checkList - optional list of paths divided by space to check presence of before removal
  2308. const jsonFilter = (function jsonFilterModule() {
  2309. const _log = (() => {
  2310. if (!jsf.AccessStatistics)
  2311. return () => null;
  2312. const counter = {};
  2313. const counterToString = () => Object.entries(counter).map(a => `\n * ${a.join(': ')}`).join('');
  2314. let lock = 0;
  2315. return async function _log(path) {
  2316. counter[path] = (counter[path] || 0) + 1;
  2317. lock++;
  2318. setTimeout(() => {
  2319. lock--;
  2320. if (lock === 0)
  2321. _console.log('JSON filters:', counterToString());
  2322. }, 3333);
  2323. };
  2324. })();
  2325.  
  2326. const isObjecty = o => (typeof o === 'object' || typeof o === 'function') && o !== null;
  2327.  
  2328. function parsePath(root, path) {
  2329. let pos;
  2330. pos = path.indexOf('.');
  2331. for (let name; pos > 0;) {
  2332. name = path.slice(0, pos);
  2333. if (!isObjecty(root[name]))
  2334. break;
  2335. root = root[name];
  2336. path = path.slice(pos + 1);
  2337. pos = path.indexOf('.');
  2338. }
  2339. return [pos < 0 && _hasOwnProperty(root, path), root, path];
  2340. }
  2341.  
  2342. const filterList = [];
  2343.  
  2344. function filter(result) {
  2345. if (!isObjecty(result))
  2346. return result;
  2347.  
  2348. const pathNotInObject = path => !(parsePath(result, path)[0]);
  2349. const removePathInObject = path => {
  2350. let [exist, root, name] = parsePath(result, path);
  2351. if (exist) {
  2352. delete root[name];
  2353. _log(path);
  2354. }
  2355. };
  2356. for (let list of filterList) {
  2357. if (list.check && list.check.some(pathNotInObject))
  2358. return result;
  2359. list.remove.forEach(removePathInObject);
  2360. }
  2361.  
  2362. return result;
  2363. }
  2364.  
  2365.  
  2366. let wrapped = false;
  2367.  
  2368. function jsonFilter(removeList, checkList) {
  2369. filterList.push({
  2370. remove: removeList.split(/\s/),
  2371. check: checkList ? checkList.split(/\s/) : undefined
  2372. });
  2373.  
  2374. if (wrapped) return;
  2375. wrapped = true;
  2376.  
  2377. win.JSON.parse = new Proxy(win.JSON.parse, {
  2378. apply(fun, that, args) {
  2379. return filter(_apply(fun, that, args));
  2380. }
  2381. });
  2382.  
  2383. win.Response.prototype.json = new Proxy(win.Response.prototype.json, {
  2384. apply(fun, that, args) {
  2385. let promise = _apply(fun, that, args);
  2386. promise.then(res => filter(res));
  2387. return promise;
  2388. }
  2389. });
  2390. }
  2391. jsonFilter.toString = () => `const jsonFilter = (${jsonFilterModule.toString()})()`;
  2392. return jsonFilter;
  2393. })();
  2394.  
  2395. function zmcPlug(tConf) {
  2396. // enable Emcode debug mode in ZMCTrack code (just to see it in the log)
  2397. const _RegExpToString = _bindCall(RegExp.prototype.toString);
  2398. String.prototype.match = new Proxy(String.prototype.match, {
  2399. apply(fun, that, args) {
  2400. let str = typeof args[0] === 'string' ? args[0] : _RegExpToString(args[0]);
  2401. if (str.includes('argon_debug'))
  2402. return true;
  2403. return _apply(fun, that, args);
  2404. }
  2405. });
  2406. // catch and overwrite API in the clean IFrame created by ZMCTrack
  2407. _Node.appendChild = new Proxy(_Node.appendChild, {
  2408. apply(fun, that, args) {
  2409. const res = _apply(fun, that, args);
  2410. if (res && res.name && res.name.startsWith('_m')) {
  2411. const zmcWin = win[res.name];
  2412. if (!zmcWin) return;
  2413. zmcWin.write = nt.func(null, 'zmc.write', true);
  2414. zmcWin.setTimeout = nt.func(null, 'zmc.setTimeout', true);
  2415. zmcWin.document.addEventListener = nt.func(null, 'zmc.document.addEventListener', true);
  2416. zmcWin.XMLHttpRequest.prototype.open = nt.func(null, 'zmc.XMLHttpRequest.prototype.open', true);
  2417. zmcWin.XMLHttpRequest.prototype.send = nt.func(null, 'zmc.XMLHttpRequest.prototype.send', true);
  2418. }
  2419. return res;
  2420. }
  2421. });
  2422. // "predict" names of zmctrack frames on certain domains which use date-based frame names
  2423. // id - some fixed number, zone - server's timezone (hours), step - how often name changes (minutes)
  2424. // range - period in hours to cover from -range/2 to +range/2
  2425. if (tConf) {
  2426. let {
  2427. id,
  2428. zone = 2,
  2429. step = 5,
  2430. range = 3,
  2431. offset = 0
  2432. } = tConf;
  2433. const pad = n => n.toString().padStart(2, '0');
  2434. const m2ms = x => x * 60 * 1000;
  2435. const d = new Date();
  2436. d.setTime(Math.floor(d.getTime() / m2ms(step)) * m2ms(step) + m2ms(zone * 60) + m2ms(offset));
  2437. const define = d => {
  2438. nt.define(`n${pad(
  2439. d.getUTCMonth() + 1
  2440. )}${pad(
  2441. d.getUTCDate()
  2442. )}${pad(
  2443. d.getUTCHours()
  2444. )}${pad(
  2445. d.getUTCMinutes()
  2446. )}${(
  2447. id ? `_${id}` : ''
  2448. )}`, null);
  2449. };
  2450. const time = d.getTime();
  2451. for (let n = -Math.floor(range * 30 / step); n <= Math.floor(range * 30 / step); n += 1) {
  2452. d.setTime(time + n * m2ms(step));
  2453. define(d);
  2454. }
  2455. }
  2456. }
  2457.  
  2458. function documentRewrite(pattern, substitute) {
  2459. /* jshint -W060 */ // document.write is a form of evil, a necessary evil in this case
  2460. const inject = (pattern, substitute) => {
  2461. let xhr = new XMLHttpRequest();
  2462. xhr.open('GET', location.href);
  2463. xhr.onload = () => {
  2464. document.close();
  2465. //console.log(xhr.responseText.match(pattern));
  2466. document.write(xhr.responseText.replace(pattern, substitute));
  2467. document.close();
  2468. };
  2469. xhr.send();
  2470. };
  2471. /* jshint +W060 */
  2472. const style = [
  2473. '@keyframes spinner { 0% { transform: translate3d(-50%, -50%, 0) rotate(0deg); } 100% { transform: translate3d(-50%, -50%, 0) rotate(360deg); } }',
  2474. '.spinner::before { animation: 1.5s linear infinite spinner; animation-play-state: running;',
  2475. 'content: ""; border: solid 3px #dedede; border-bottom-color: #EF6565; border-radius: 50%;',
  2476. 'height: 10vh; width: 10vh; left: 50%; top: 50%; position: absolute; transform: translate3d(-50%, -50%, 0); };'
  2477. ].join('');
  2478. _document.write(`<html><head><script>(${inject.toString()})(${pattern.toString()},'${substitute}')</script>`);
  2479. _document.write(`<style>${style}</style></head><body><div class="spinner"></div></body></html>`);
  2480. }
  2481.  
  2482. // === Scripts for specific domains ===
  2483.  
  2484. const scripts = {
  2485. // Prevent Popups
  2486. preventPopups: {
  2487. other: 'biqle.ru, chaturbate.com, dfiles.ru, eporner.eu, hentaiz.org, mirrorcreator.com, online-multy.ru' +
  2488. 'radikal.ru, rumedia.ws, tapehub.tech, thepiratebay.org, unionpeer.com, zippyshare.com',
  2489. now: preventPopups
  2490. },
  2491. // Prevent Popunders (background redirect)
  2492. preventPopunders: {
  2493. other: 'lostfilm-online.ru, mediafire.com, megapeer.org, megapeer.ru, perfectgirls.net',
  2494. now: preventPopunders
  2495. },
  2496. // zmctrack remover
  2497. zmcDocumentRewriteS: {
  2498. other: [ // disabled on domains where my script somehow still catches zmctrack requests
  2499. // 112.ua,24boxing.com.ua,bilshe.com,buhgalter.com.ua,buhgalter911.com,businessua.com,dengi.ua,ditey.com
  2500. // f1analytic.com,facenews.ua,football-ukraine.com,footballgazeta.com,footballtransfer.com.ua
  2501. // glianec.com,gorod.dp.ua,lifedon.com.ua,nashamama.com,stravy.net,u-news.com.ua,vsetv.com,zdorovia.com.ua
  2502. 'enovosty.com,epravda.com.ua,eurointegration.com.ua,football24.ua',
  2503. 'kp.ua,ostro.org,real-vin.com,www.ukr.net'
  2504. ].join(','),
  2505. now: () => {
  2506. documentRewrite(/<iframe\sname="n\d+(_\d+)?"\sstyle="display:none"><\/iframe><script(\s+[^>]+)?>.*?<\/script>/, '<!-- removed -->');
  2507. }
  2508. },
  2509. zmcPlug: {
  2510. other: [
  2511. // censor.net,newsyou.info
  2512. '4mama.ua,beauty.ua,eknigi.org,forumodua.com,internetua.com,okino.ua',
  2513. 'sinoptik.ua,toneto.net,tvgid.ua,tvoymalysh.com.ua,udoktora.net'
  2514. ].join(','),
  2515. now: () => {
  2516. if (GM_info.scriptHandler === 'Violentmonkey')
  2517. documentRewrite(/ /, ' ');
  2518. zmcPlug();
  2519. }
  2520. },
  2521. zmcPlugTime: {
  2522. other: [
  2523. 'avtovod.com.ua,besplatka.ua,bigmir.net,gismeteo.tld,hvylya.net,inforesist.org,isport.ua',
  2524. 'kolobok.ua,kriminal.tv,mport.ua,nnovosti.info,smak.ua,strana.ua,tochka.net,tv.ua,viva.ua'
  2525. ].join(','),
  2526. now: () => {
  2527. let is = name => location.hostname === name || location.hostname.includes(name);
  2528. if ([
  2529. ['avtovod.com', 'id', 12497],
  2530. ['besplatka.ua', 'step', 1, 'range', 2.2],
  2531. ['gismeteo', 'id', 11495, 'zone', 0],
  2532. ['hvylya.net', 'zone', 1, 'step', 60, 'range', 4, 'offset', 24],
  2533. ['inforesist.org', 'zone', 1.5, 'step', 30, 'range', 5],
  2534. ['kriminal.tv', 'id', 12086],
  2535. ['nnovosti.info', 'id', 12125],
  2536. ['strana.ua', 'id', 12161],
  2537. ['tochka.net', 'step', 1, 'range', 2.2],
  2538. ['viva.ua', 'id', 11560]
  2539. ].some(e => is(e[0]) && !zmcPlug( // object from flat key/value array
  2540. e.reduceRight((o, x, i) => (o[i % 2 ? x : 'x'] = i % 2 ? o.x : x, o), {})
  2541. ))) return;
  2542. zmcPlug({});
  2543. }
  2544. },
  2545. // custom zmc-related fixes
  2546. 'i.ua': () => documentRewrite(/<script type="application\/javascript">\(function\(\) {var _0x.*?}\)\(\)<\/script>/, '<!-- removed -->'),
  2547. 'kzblow.info': () => documentRewrite(/<script>\(function\(\w\w,.*?['"]n\d+['"]\);<\/script>/, '<!-- removed -->'),
  2548. 'nv.ua': () => documentRewrite(/<script>\(function\(\w\w,.*?['"]n\d+['"]\);<\/script>/, '<!-- removed -->'),
  2549. // disables ads when specific cookies are set
  2550. 'liga.net': () => (_document.cookie = 'isShowAd=false; domain=.liga.net', _document.cookie = 'is_login=true; domain=.liga.net'),
  2551. // Adnet script cause infinite page reload in Fx
  2552. 'pravda.com.ua': () => documentRewrite(/<iframe\sname="n\d+(_\d+)?"\sstyle="display:none"><.*?<\/script>|<script>\nfunction\sAdnet[\s\S]*?<\/script>/gm, '<!-- removed -->'),
  2553. // disables ads if screen width is below 1200
  2554. 'segodnya.ua': () => nt.define('document.documentElement.clientWidth', 1111),
  2555.  
  2556. // PopMix (both types of popups encountered on site)
  2557. 'openload.co': {
  2558. other: 'oload.tv, oload.info, openload.co.com',
  2559. now() {
  2560. if (inIFrame) {
  2561. nt.define('BetterJsPop', {
  2562. add(a, b) {
  2563. _console.trace('BetterJsPop.add(%o, %o)', a, b);
  2564. },
  2565. config(o) {
  2566. _console.trace('BetterJsPop.config(%o)', o);
  2567. },
  2568. Browser: {
  2569. isChrome: true
  2570. }
  2571. });
  2572. nt.define('isSandboxed', nt.func(null, 'isSandboxed'));
  2573. nt.define('adblock', false);
  2574. nt.define('adblock2', false);
  2575. } else preventPopMix();
  2576. }
  2577. },
  2578.  
  2579. 'turbobit.net': preventPopMix,
  2580.  
  2581. 'tapochek.net': () => {
  2582. // workaround for moradu.com/apu.php load error handler script, not sure which ad network is this
  2583. let _appendChild = Object.getOwnPropertyDescriptor(_Node, 'appendChild');
  2584. let _appendChild_value = _appendChild.value;
  2585. _appendChild.value = function appendChild(node) {
  2586. if (this === _document.body)
  2587. if ((node instanceof HTMLScriptElement || node instanceof HTMLStyleElement) &&
  2588. /^https?:\/\/[0-9a-f]{15}\.com\/\d+(\/|\.css)$/.test(node.src) ||
  2589. node instanceof HTMLDivElement && node.style.zIndex > 900000 &&
  2590. node.style.backgroundImage.includes('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'))
  2591. throw '...eenope!';
  2592. return _appendChild_value.apply(this, arguments);
  2593. };
  2594. Object.defineProperty(_Node, 'appendChild', _appendChild);
  2595.  
  2596. // disable window focus tricks and changing location
  2597. let focusHandlerName = /\WfocusAchieved\(/;
  2598. let _setInterval = win.setInterval;
  2599. win.setInterval = (...args) => {
  2600. if (args.length && focusHandlerName.test(_toString(args[0]))) {
  2601. _console.log('skip setInterval for', ...args);
  2602. return -1;
  2603. }
  2604. return _setInterval(...args);
  2605. };
  2606. let _addEventListener = win.addEventListener;
  2607. win.addEventListener = function (...args) {
  2608. if (args.length && args[0] === 'focus' && focusHandlerName.test(_toString(args[1]))) {
  2609. _console.log('skip addEventListener for', ...args);
  2610. return undefined;
  2611. }
  2612. return _addEventListener.apply(this, args);
  2613. };
  2614.  
  2615. // generic popup prevention
  2616. preventPopups();
  2617. },
  2618.  
  2619. // = other ======================================================================================
  2620.  
  2621. '1tv.ru': {
  2622. other: 'mediavitrina.ru',
  2623. now: () => scriptLander(() => {
  2624. nt.define('EUMPAntiblockConfig', nt.proxy({
  2625. url: '//www.1tv.ru/favicon.ico'
  2626. }));
  2627. nt.define('Object.prototype.disableSeek', nt.func(undefined, 'disableSeek'));
  2628. //nt.define('preroll', undefined);
  2629.  
  2630. let _EUMP;
  2631. const _EUMP_set = x => {
  2632. if (x === _EUMP)
  2633. return true;
  2634. let _plugins = x.plugins;
  2635. Object.defineProperty(x, 'plugins', {
  2636. enumerable: true,
  2637. get() {
  2638. return _plugins;
  2639. },
  2640. set(vl) {
  2641. if (vl === _plugins)
  2642. return true;
  2643. nt.defineOn(vl, 'antiblock', function (player, opts) {
  2644. const antiblock = nt.proxy({
  2645. opts: opts,
  2646. readyState: 'ready',
  2647. isEUMPPlugin: true,
  2648. detected: nt.func(false, 'antiblock.detected'),
  2649. currentWeight: nt.func(0, 'antiblock.currentWeight')
  2650. });
  2651. player.antiblock = antiblock;
  2652. return antiblock;
  2653. }, 'EUMP.plugins.');
  2654. _plugins = vl;
  2655. }
  2656. });
  2657. _EUMP = x;
  2658. return true;
  2659. };
  2660. if ('EUMP' in win)
  2661. _EUMP_set(win.EUMP);
  2662. Object.defineProperty(win, 'EUMP', {
  2663. enumerable: true,
  2664. get() {
  2665. return _EUMP;
  2666. },
  2667. set: _EUMP_set
  2668. });
  2669.  
  2670. let _EUMPVGTRK;
  2671. const _EUMPVGTRK_set = x => {
  2672. if (x === _EUMPVGTRK)
  2673. return true;
  2674. if (x && x.prototype) {
  2675. if ('generatePrerollUrls' in x.prototype)
  2676. nt.defineOn(x.prototype, 'generatePrerollUrls', nt.func(null, 'EUMPVGTRK.generatePrerollUrls'), 'EUMPVGTRK.prototype.', {
  2677. enumerable: false
  2678. });
  2679. if ('sendAdsEvent' in x.prototype)
  2680. nt.defineOn(x.prototype, 'sendAdsEvent', nt.func(null, 'EUMPVGTRK.sendAdsEvent'), 'EUMPVGTRK.prototype.', {
  2681. enumerable: false
  2682. });
  2683. }
  2684. _EUMPVGTRK = x;
  2685. return true;
  2686. };
  2687. if ('EUMPVGTRK' in win)
  2688. _EUMPVGTRK_set(win.EUMPVGTRK);
  2689. Object.defineProperty(win, 'EUMPVGTRK', {
  2690. enumerable: true,
  2691. get() {
  2692. return _EUMPVGTRK;
  2693. },
  2694. set: _EUMPVGTRK_set
  2695. });
  2696. }, nullTools)
  2697. },
  2698.  
  2699. '24smi.org': () => scriptLander(() => selectiveCookies('has_adblock'), selectiveCookies),
  2700.  
  2701. '2picsun.ru': {
  2702. other: 'pics2sun.ru, 3pics-img.ru',
  2703. now() {
  2704. Object.defineProperty(navigator, 'userAgent', {
  2705. value: 'googlebot'
  2706. });
  2707. }
  2708. },
  2709.  
  2710. '4pda.ru': {
  2711. now() {
  2712. // https://greasyfork.org/en/scripts/14470-4pda-unbrender
  2713. const isForum = location.pathname.startsWith('/forum/'),
  2714. remove = node => (node && node.parentNode.removeChild(node)),
  2715. hide = node => (node && (node.style.display = 'none'));
  2716.  
  2717. selectiveCookies('viewpref');
  2718. abortExecution.inlineScript('document.querySelector', {
  2719. pattern: /\(document(,window)?\);/
  2720. });
  2721.  
  2722. function cleaner(log) {
  2723. HeaderAds: {
  2724. // hide ads above HEADER
  2725. let nav = _document.querySelector('.menu-main-item');
  2726. while (nav && (nav.parentNode !== _de))
  2727. if (!nav.parentNode.querySelector('article, .container[itemtype$="Article"]'))
  2728. nav = nav.parentNode;
  2729. else break;
  2730. if (!nav || (nav.parentNode === _de)) {
  2731. if (log) _console.warn('Unable to locate header element');
  2732. break HeaderAds;
  2733. }
  2734. if (log) _console.log('Processing header:', nav);
  2735. for (let itm of nav.parentNode.children)
  2736. if (itm !== nav)
  2737. hide(itm);
  2738. else break;
  2739. }
  2740.  
  2741. FixNavMenu: {
  2742. // hide ad link from the navigation
  2743. let ad = _document.querySelector('.menu-main-item > a > svg');
  2744. if (!ad) {
  2745. if (log) _console.warn('Unable to locate menu ad item');
  2746. break FixNavMenu;
  2747. } else {
  2748. ad = ad.parentNode.parentNode;
  2749. hide(ad);
  2750. }
  2751. }
  2752.  
  2753. SidebarAds: {
  2754. // remove ads from sidebar
  2755. let aside = _document.querySelectorAll('[class]:not([id]) > [id]:not([class]) > :first-child + :last-child:not(.v-panel)');
  2756. if (!aside.length) {
  2757. if (log) _console.warn('Unable to locate sidebar');
  2758. break SidebarAds;
  2759. }
  2760. let post;
  2761. for (let side of aside) {
  2762. if (log) _console.log('Processing potential sidebar:', side);
  2763. for (let itm of Array.from(side.children)) {
  2764. post = itm.classList.contains('post');
  2765. if (post) continue;
  2766. if (itm.querySelector('iframe') || !itm.children.length)
  2767. remove(itm);
  2768. let script = itm.querySelector('script');
  2769. if (itm.querySelector('a[target="_blank"] > img') ||
  2770. script && script.src === '' && (script.type === 'text/javascript' || !script.type) &&
  2771. script.textContent.includes('document'))
  2772. hide(itm);
  2773. }
  2774. }
  2775. }
  2776. }
  2777.  
  2778. const cln = setInterval(() => cleaner(false), 50);
  2779.  
  2780. // hide banner next to logo
  2781. if (isForum)
  2782. createStyle('div[class]:not([id]) tr[valign="top"] > td:last-child { display: none !important }');
  2783. // clean page
  2784. window.addEventListener(
  2785. 'DOMContentLoaded',
  2786. function () {
  2787. clearInterval(cln);
  2788. const width = () => win.innerWidth || _de.clientWidth || _document.body.clientWidth || 0,
  2789. height = () => win.innerHeight || _de.clientHeight || _document.body.clientHeight || 0;
  2790.  
  2791. if (isForum) {
  2792. // hide banner next to logo
  2793. //let itm = _document.querySelector('#logostrip');
  2794. //if (itm) hide(itm.parentNode.nextSibling);
  2795. // clear background in the download frame
  2796. if (location.pathname.startsWith('/forum/dl/')) {
  2797. let setBackground = node => _setAttribute(
  2798. node,
  2799. 'style', (_getAttribute(node, 'style') || '') +
  2800. ';background-color:#4ebaf6!important'
  2801. );
  2802. setBackground(_document.body);
  2803. for (let itm of _document.querySelectorAll('body > div'))
  2804. if (!itm.querySelector('.dw-fdwlink, .content') && !itm.classList.contains('footer'))
  2805. remove(itm);
  2806. else
  2807. setBackground(itm);
  2808. }
  2809. // exist from DOMContentLoaded since the rest is not for forum
  2810. return;
  2811. }
  2812.  
  2813. cleaner(false);
  2814.  
  2815. _document.body.setAttribute('style', (_document.body.getAttribute('style') || '') + ';background-color:#E6E7E9!important');
  2816.  
  2817. let extra = 'background-image:none!important;background-color:transparent!important',
  2818. fakeStyles = new WeakMap(),
  2819. styleProxy = {
  2820. get(target, prop) {
  2821. return fakeStyles.get(target)[prop] || target[prop];
  2822. },
  2823. set(target, prop, value) {
  2824. let fakeStyle = fakeStyles.get(target);
  2825. ((prop in fakeStyle) ? fakeStyle : target)[prop] = value;
  2826. return true;
  2827. }
  2828. };
  2829. for (let itm of _document.querySelectorAll('[id]:not(A), A')) {
  2830. if (!(itm.offsetWidth > 0.95 * width() &&
  2831. itm.offsetHeight > 0.85 * height()))
  2832. continue;
  2833. if (itm.tagName !== 'A') {
  2834. fakeStyles.set(itm.style, {
  2835. 'backgroundImage': itm.style.backgroundImage,
  2836. 'backgroundColor': itm.style.backgroundColor
  2837. });
  2838.  
  2839. try {
  2840. Object.defineProperty(itm, 'style', {
  2841. value: new Proxy(itm.style, styleProxy),
  2842. enumerable: true
  2843. });
  2844. } catch (e) {
  2845. _console.log('Unable to protect style property.', e);
  2846. }
  2847.  
  2848. _setAttribute(itm, 'style', `${(_getAttribute(itm, 'style') || '')};${extra}`);
  2849. }
  2850. if (itm.tagName === 'A')
  2851. _setAttribute(itm, 'style', 'display:none!important');
  2852. }
  2853. }
  2854. );
  2855. }
  2856. },
  2857.  
  2858. 'adhands.ru': () => scriptLander(() => {
  2859. try {
  2860. let _adv;
  2861. Object.defineProperty(win, 'adv', {
  2862. get() {
  2863. return _adv;
  2864. },
  2865. set(val) {
  2866. _console.log('Blocked advert on adhands.ru.');
  2867. nt.defineOn(val, 'advert', '', 'adv.');
  2868. _adv = val;
  2869. }
  2870. });
  2871. } catch (ignore) {
  2872. if (!win.adv)
  2873. _console.log('Unable to locate advert on adhands.ru.');
  2874. else {
  2875. _console.log('Blocked advert on adhands.ru.');
  2876. nt.define('adv.advert', '');
  2877. }
  2878. }
  2879. }, nullTools),
  2880.  
  2881. 'all-episodes.org': () => {
  2882. nt.define('perROS', 0); // blocks access when = 1
  2883. nt.define('idm', -1); // blocks quality when >= 0
  2884. nt.define('advtss', nt.proxy({
  2885. offsetHeight: 200,
  2886. offsetWidth: 200
  2887. }, 'advtss'));
  2888. // wrap player to prevent some events and interactions
  2889. let _playerInstance = win.playerInstance;
  2890. Object.defineProperty(win, 'playerInstance', {
  2891. get() {
  2892. return _playerInstance;
  2893. },
  2894. set(vl) {
  2895. _console.log('player =', vl, vl.on, vl.getAdBlock);
  2896. vl.on = new Proxy(vl.on, {
  2897. apply(fun, that, args) {
  2898. if (/^(ad[A-Z]|before(Play|Complete))/.test(args[0]))
  2899. return;
  2900. //_console.log('on', ...args);
  2901. return _apply(fun, that, args);
  2902. }
  2903. });
  2904. nt.defineOn(vl, 'getAdBlock', nt.func(false, 'playerInstance.getAdBlock'), 'playerInstance.getAdBlock');
  2905. _playerInstance = vl;
  2906. }
  2907. });
  2908. },
  2909.  
  2910. 'allhentai.ru': () => {
  2911. preventPopups();
  2912. scriptLander(() => {
  2913. selectiveEval();
  2914. let _onerror = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onerror');
  2915. if (!_onerror)
  2916. return;
  2917. _onerror.set = (...args) => _console.log(args[0].toString());
  2918. Object.defineProperty(HTMLElement.prototype, 'onerror', _onerror);
  2919. }, selectiveEval);
  2920. },
  2921.  
  2922. 'allmovie.pro': {
  2923. other: 'rufilmtv.org',
  2924. dom() {
  2925. // pretend to be Android to make site use different played for ads
  2926. if (isSafari)
  2927. return;
  2928. Object.defineProperty(navigator, 'userAgent', {
  2929. get() {
  2930. 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';
  2931. },
  2932. enumerable: true
  2933. });
  2934. }
  2935. },
  2936.  
  2937. 'ati.su': () => scriptLander(() => {
  2938. nt.define('Object.prototype.advManager', nt.proxy({}, 'advManager'));
  2939. }),
  2940.  
  2941. 'audioportal.su': {
  2942. now() {
  2943. createStyle('#blink2 { display: none !important }');
  2944. },
  2945. dom() {
  2946. let links = _document.querySelectorAll('a[onclick*="clickme("]');
  2947. if (!links) return;
  2948. for (let link of links)
  2949. win.clickme(link);
  2950. }
  2951. },
  2952.  
  2953. 'auto.ru': () => {
  2954. let words = /Реклама|Яндекс.Директ|yandex_ad_/;
  2955. let userAdsListAds = (
  2956. '.listing-list > .listing-item,' +
  2957. '.listing-item_type_fixed.listing-item'
  2958. );
  2959. let catalogAds = (
  2960. 'div[class*="layout_catalog-inline"],' +
  2961. 'div[class$="layout_horizontal"]'
  2962. );
  2963. let otherAds = (
  2964. '.advt_auto,' +
  2965. '.sidebar-block,' +
  2966. '.pager-listing + div[class],' +
  2967. '.card > div[class][style],' +
  2968. '.sidebar > div[class],' +
  2969. '.main-page__section + div[class],' +
  2970. '.listing > tbody'
  2971. );
  2972. gardener(userAdsListAds, words, {
  2973. root: '.listing-wrap',
  2974. observe: true
  2975. });
  2976. gardener(catalogAds, words, {
  2977. root: '.catalog__page,.content__wrapper',
  2978. observe: true
  2979. });
  2980. gardener(otherAds, words);
  2981. nt.define('Object.prototype.yaads', undefined);
  2982. nt.define('Object.prototype.initYaDirect', undefined);
  2983. nt.define('Object.prototype.direct', nt.proxy({}, 'Yandex.direct'));
  2984. },
  2985.  
  2986. 'avito.ru': () => scriptLander(() => selectiveCookies('abp|cmtchd|crookie|is_adblock'), selectiveCookies),
  2987.  
  2988. 'di.fm': () => scriptLander(() => {
  2989. let log = false;
  2990. // wrap global app object to catch registration of specific modules
  2991. let _di = win.di;
  2992. Object.defineProperty(win, 'di', {
  2993. get() {
  2994. return _di;
  2995. },
  2996. set(vl) {
  2997. if (vl === _di)
  2998. return;
  2999. if (log) _console.trace('di =', vl);
  3000. _di = new Proxy(vl, {
  3001. set(di, name, vl) {
  3002. if (vl === di[name])
  3003. return true;
  3004. if (name === 'app') {
  3005. if (log) _console.trace(`di.${name} =`, vl);
  3006. if (!('module' in vl))
  3007. return;
  3008. vl.module = new Proxy(vl.module, {
  3009. apply(module, that, args) {
  3010. if (/Wall|Banner|Detect|WebplayerApp\.Ads/.test(args[0])) {
  3011. let name = args[0];
  3012. if (log) _console.log('wrap', name, 'module');
  3013. if (typeof args[1] === 'function')
  3014. args[1] = new Proxy(args[1], {
  3015. apply(fun, that, args) {
  3016. if (args[0]) // module object
  3017. args[0].start = () => _console.log('Skipped start of', name);
  3018. return Reflect.apply(fun, that, args);
  3019. }
  3020. });
  3021. } // else log && _console.log('loading module', args[0]);
  3022. if (args[0] === 'Modals' && typeof args[1] === 'function') {
  3023. if (log) _console.log('wrap', name, 'module');
  3024. args[1] = new Proxy(args[1], {
  3025. apply(fun, that, args) {
  3026. if ('commands' in args[1] && 'setHandlers' in args[1].commands &&
  3027. !Object.hasOwnProperty.call(args[1].commands, 'setHandlers')) {
  3028. let _commands = args[1].commands;
  3029. _commands.setHandlers = new Proxy(_commands.setHandlers, {
  3030. apply(fun, that, args) {
  3031. const noopFunc = name => () => _console.log('Skipped', name, 'window');
  3032. for (let name in args[0])
  3033. if (name === 'modal:streaminterrupt' ||
  3034. name === 'modal:midroll')
  3035. args[0][name] = noopFunc(name);
  3036. delete _commands.setHandlers;
  3037. return Reflect.apply(fun, that, args);
  3038. }
  3039. });
  3040. }
  3041. return Reflect.apply(fun, that, args);
  3042. }
  3043. });
  3044. }
  3045. return Reflect.apply(module, that, args);
  3046. }
  3047. });
  3048. }
  3049. di[name] = vl;
  3050. }
  3051. });
  3052. }
  3053. });
  3054. // don't send errorception logs
  3055. Object.defineProperty(win, 'onerror', {
  3056. set(vl) {
  3057. if (log) _console.trace('Skipped global onerror callback:', vl);
  3058. }
  3059. });
  3060. }),
  3061.  
  3062. 'draug.ru': {
  3063. other: 'vargr.ru',
  3064. now: () => scriptLander(() => {
  3065. if (location.pathname === '/pop.html')
  3066. win.close();
  3067. createStyle({
  3068. '#timer_1': {
  3069. display: 'none !important'
  3070. },
  3071. '#timer_2': {
  3072. display: 'block !important'
  3073. }
  3074. });
  3075. let _contentWindow = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, 'contentWindow');
  3076. let _get_contentWindow = _bindCall(_contentWindow.get);
  3077. _contentWindow.get = function () {
  3078. let res = _get_contentWindow(this);
  3079. if (res.location.href === 'about:blank')
  3080. res.document.write = (...args) => _console.log('Skipped iframe.write(', ...args, ')');
  3081. return res;
  3082. };
  3083. Object.defineProperty(HTMLIFrameElement.prototype, 'contentWindow', _contentWindow);
  3084. }),
  3085. dom() {
  3086. let list = _querySelectorAll('div[id^="yandex_rtb_"], .adsbygoogle');
  3087. list.forEach(node => _console.log('Removed:', node.parentNode.parentNode.removeChild(node.parentNode)));
  3088. }
  3089. },
  3090.  
  3091. 'drive2.ru': () => {
  3092. gardener('.c-block:not([data-metrika="recomm"]),.o-grid__item', />Реклама<\//i);
  3093. scriptLander(() => {
  3094. selectiveCookies();
  3095. let _d2;
  3096. Object.defineProperty(win, 'd2', {
  3097. get() {
  3098. return _d2;
  3099. },
  3100. set(vl) {
  3101. if (vl === _d2)
  3102. return true;
  3103. _d2 = new Proxy(vl, {
  3104. set(target, prop, val) {
  3105. if (['brandingRender', 'dvReveal', '__dv'].includes(prop))
  3106. val = () => null;
  3107. target[prop] = val;
  3108. return true;
  3109. }
  3110. });
  3111. }
  3112. });
  3113. // obfuscated Yandex.Direct
  3114. nt.define('Object.prototype.initYaDirect', undefined);
  3115. }, nullTools, selectiveCookies);
  3116. },
  3117.  
  3118. 'eurogamer.tld': {
  3119. other: 'metabomb.net, usgamer.net',
  3120. now: () => scriptLander(() => {
  3121. abortExecution.inlineScript('_sp_');
  3122. selectiveCookies('sp');
  3123. }, selectiveCookies, abortExecution)
  3124. },
  3125.  
  3126. 'fastpic.ru': () => {
  3127. // Had to obfuscate property name to avoid triggering anti-obfuscation on greasyfork.org -_- (Exception 403012)
  3128. nt.define(`_0x${'4955'}`, []);
  3129. },
  3130.  
  3131. 'fishki.net': () => {
  3132. scriptLander(() => {
  3133. const fishki = {};
  3134. const adv = nt.proxy({
  3135. afterAdblockCheck: nt.func(null, 'fishki.afterAdblockCheck'),
  3136. refreshFloat: nt.func(null, 'fishki.refreshFloat')
  3137. });
  3138. nt.defineOn(fishki, 'adv', adv, 'fishki.');
  3139. nt.defineOn(fishki, 'is_adblock', false, 'fishki.');
  3140. nt.define('fishki', fishki);
  3141. nt.define('Object.prototype.detect', nt.func(undefined, 'detect'));
  3142. win.Object.defineProperty = new Proxy(win.Object.defineProperty, {
  3143. apply(fun, that, args) {
  3144. if (['is_adblock', 'adv'].includes(args[1]) || args[0] === adv)
  3145. return;
  3146. return _apply(fun, that, args);
  3147. }
  3148. });
  3149. }, nullTools);
  3150. gardener('.drag_list > .drag_element, .list-view > .paddingtop15, .post-wrap', /543769|Новости\sпартнеров|Полезная\sреклама/);
  3151. },
  3152.  
  3153. 'forbes.com': () => {
  3154. createStyle(['fbs-ad[ad-id], .top-ad-container, .fbs-ad-wrapper, .footer-ad-labeling, .ad-rail, .ad-unit { display: none !important; }']);
  3155. nt.define('Object.prototype.isAdLight', true);
  3156. nt.define('Object.prototype.initializeAd', nt.func(undefined, '?.initializeAd'));
  3157. win.getComputedStyle = new Proxy(win.getComputedStyle, {
  3158. apply(fun, that, args) {
  3159. let res = _apply(fun, that, args);
  3160. if (res.display === 'none')
  3161. nt.defineOn(res, 'display', 'block', 'getComputedStyle().');
  3162. if (res.visibility === 'hidden')
  3163. nt.defineOn(res, 'visibility', 'visible', 'getComputedStyle().');
  3164. return res;
  3165. }
  3166. });
  3167. win.CSSStyleDeclaration.prototype.getPropertyValue = new Proxy(win.CSSStyleDeclaration.prototype.getPropertyValue, {
  3168. apply(fun, that, args) {
  3169. let res = _apply(fun, that, args);
  3170. if (args[0] === 'display' && res === 'none')
  3171. return 'block';
  3172. if (args[0] === 'visibility' && res === 'hidden')
  3173. return 'visible';
  3174. return res;
  3175. }
  3176. });
  3177. },
  3178.  
  3179. 'friends.in.ua': () => scriptLander(() => {
  3180. Object.defineProperty(win, 'need_warning', {
  3181. get() {
  3182. return 0;
  3183. },
  3184. set() {}
  3185. });
  3186. }),
  3187.  
  3188. 'gamerevolution.com': () => {
  3189. const _clientHeight = Object.getOwnPropertyDescriptor(_Element, 'clientHeight');
  3190. _clientHeight.get = new Proxy(_clientHeight.get, {
  3191. apply(...args) {
  3192. return _apply(...args) || 1;
  3193. }
  3194. });
  3195. Object.defineProperty(_Element, 'clientHeight', _clientHeight);
  3196.  
  3197. const toReplace = [
  3198. 'blockerDetected', 'disableDetected', 'hasAdBlocker',
  3199. 'hasBlockerFlag', 'hasDisabledAdBlocker', 'hasBlocker'
  3200. ];
  3201. win.Object.defineProperty = new Proxy(win.Object.defineProperty, {
  3202. apply(fun, that, args) {
  3203. if (toReplace.includes(args[1])) {
  3204. args[2] = {
  3205. value() {
  3206. return false;
  3207. }
  3208. };
  3209. console.log(args);
  3210. }
  3211. return _apply(fun, that, args);
  3212. }
  3213. });
  3214. },
  3215.  
  3216. 'gamersheroes.com': () => abortExecution.inlineScript('document.createElement', {
  3217. pattern: /window\[\w+\(\[(\d+,?\s?)+\],\s?\w+\)\]/
  3218. }),
  3219.  
  3220. 'gidonline.club': () => createStyle('.tray > div[style] {display: none!important}'),
  3221.  
  3222. 'glav.su': () => scriptLander(() => {
  3223. abortExecution.onSet('abd');
  3224. abortExecution.onSet('script1');
  3225. }, abortExecution),
  3226.  
  3227. 'gorodrabot.ru': () => scriptLander(() => {
  3228. abortExecution.onGet('Object.prototype.yaads');
  3229. abortExecution.onGet('Object.prototype.initYaDirect');
  3230. }, abortExecution),
  3231.  
  3232. 'hdgo.cc': {
  3233. other: '46.30.43.38, couber.be',
  3234. now() {
  3235. (new MutationObserver(
  3236. ms => {
  3237. let m, node;
  3238. for (m of ms)
  3239. for (node of m.addedNodes)
  3240. if (node.tagName instanceof HTMLScriptElement && _getAttribute(node, 'onerror') !== null)
  3241. node.removeAttribute('onerror');
  3242. }
  3243. )).observe(_document.documentElement, {
  3244. childList: true,
  3245. subtree: true
  3246. });
  3247. }
  3248. },
  3249.  
  3250. 'gamepur.com': () => {
  3251. nt.define('ga', nt.func(null, 'ga'));
  3252. win.Object.defineProperty = new Proxy(win.Object.defineProperty, {
  3253. apply(fun, that, args) {
  3254. if (typeof args[1] === 'string' &&
  3255. (args[1] === 'hasAdblocker' || args[1] === 'blockerDetected'))
  3256. throw new TypeError(`Cannot read property '${args[1]}' of undefined`);
  3257. return Reflect.apply(fun, that, args);
  3258. }
  3259. });
  3260. },
  3261.  
  3262. 'hdrezka.ag': () => {
  3263. Object.defineProperty(win, 'ab', {
  3264. value: false,
  3265. enumerable: true
  3266. });
  3267. gardener('div[id][onclick][onmouseup][onmousedown]', /onmouseout/i);
  3268. },
  3269.  
  3270. 'hqq.tv': () => scriptLander(() => {
  3271. // disable anti-debugging in hqq.tv player
  3272. 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);
  3273. deepWrapAPI(root => {
  3274. // skip obfuscated stuff and a few other calls
  3275. let _setInterval = root.setInterval,
  3276. _setTimeout = root.setTimeout;
  3277. root.setInterval = (...args) => {
  3278. let fun = args[0];
  3279. if (typeof fun === 'function') {
  3280. let text = _toString(fun),
  3281. skip = text.includes('check();') || isObfuscated(text);
  3282. _console.trace('setInterval', text, 'skip', skip);
  3283. if (skip) return -1;
  3284. }
  3285. return _setInterval.apply(this, args);
  3286. };
  3287. let wrappedST = new WeakSet();
  3288. root.setTimeout = (...args) => {
  3289. let fun = args[0];
  3290. if (typeof fun === 'function') {
  3291. let text = _toString(fun),
  3292. skip = fun.name === 'check' || isObfuscated(text);
  3293. if (!wrappedST.has(fun)) {
  3294. _console.trace('setTimeout', text, 'skip', skip);
  3295. wrappedST.add(fun);
  3296. }
  3297. if (skip) return;
  3298. }
  3299. return _setTimeout.apply(this, args);
  3300. };
  3301. // skip 'debugger' call
  3302. let _eval = root.eval;
  3303. root.eval = text => {
  3304. if (typeof text === 'string' && text.includes('debugger;')) {
  3305. _console.trace('skip eval', text);
  3306. return;
  3307. }
  3308. _eval(text);
  3309. };
  3310. // Prevent RegExpt + toString trick
  3311. let _proto;
  3312. try {
  3313. _proto = root.RegExp.prototype;
  3314. } catch (ignore) {
  3315. return;
  3316. }
  3317. let _RE_tS = Object.getOwnPropertyDescriptor(_proto, 'toString');
  3318. let _RE_tSV = _RE_tS.value || _RE_tS.get();
  3319. Object.defineProperty(_proto, 'toString', {
  3320. enumerable: _RE_tS.enumerable,
  3321. configurable: _RE_tS.configurable,
  3322. get() {
  3323. return _RE_tSV;
  3324. },
  3325. set(val) {
  3326. _console.trace('Attempt to change toString for', this, 'with', _toString(val));
  3327. }
  3328. });
  3329. });
  3330. }, deepWrapAPI),
  3331.  
  3332. 'hideip.me': {
  3333. now: () => scriptLander(() => {
  3334. let _innerHTML = Object.getOwnPropertyDescriptor(_Element, 'innerHTML');
  3335. let _set_innerHTML = _innerHTML.set;
  3336. let _innerText = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'innerText');
  3337. let _get_innerText = _innerText.get;
  3338. let div = _document.createElement('div');
  3339. _innerHTML.set = function (...args) {
  3340. _set_innerHTML.call(div, args[0].replace('i', 'a'));
  3341. if (args[0] && /[рp][еe]кл/.test(_get_innerText.call(div)) ||
  3342. /(\d\d\d?\.){3}\d\d\d?:\d/.test(_get_innerText.call(this))) {
  3343. _console.log('Anti-Adblock killed.');
  3344. return true;
  3345. }
  3346. _set_innerHTML.apply(this, args);
  3347. };
  3348. Object.defineProperty(_Element, 'innerHTML', _innerHTML);
  3349. Object.defineProperty(win, 'adblock', {
  3350. get() {
  3351. return false;
  3352. },
  3353. set() {},
  3354. enumerable: true
  3355. });
  3356. let _$ = {};
  3357. let _$_map = new WeakMap();
  3358. let _gOPD = Object.getOwnPropertyDescriptor(Object, 'getOwnPropertyDescriptor');
  3359. let _val_gOPD = _gOPD.value;
  3360. _gOPD.value = function (...args) {
  3361. let _res = _val_gOPD.apply(this, args);
  3362. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery')) {
  3363. delete _res.get;
  3364. delete _res.set;
  3365. _res.value = win[args[1]];
  3366. }
  3367. return _res;
  3368. };
  3369. Object.defineProperty(Object, 'getOwnPropertyDescriptor', _gOPD);
  3370. let getJQWrap = (n) => {
  3371. let name = n;
  3372. return {
  3373. enumerable: true,
  3374. get() {
  3375. return _$[name];
  3376. },
  3377. set(x) {
  3378. if (_$_map.has(x)) {
  3379. _$[name] = _$_map.get(x);
  3380. return true;
  3381. }
  3382. if (x === _$.$ || x === _$.jQuery) {
  3383. _$[name] = x;
  3384. return true;
  3385. }
  3386. _$[name] = new Proxy(x, {
  3387. apply(t, o, args) {
  3388. let _res = t.apply(o, args);
  3389. if (_$_map.has(_res.is))
  3390. _res.is = _$_map.get(_res.is);
  3391. else {
  3392. let _is = _res.is;
  3393. _res.is = function (...args) {
  3394. if (args[0] === ':hidden')
  3395. return false;
  3396. return _is.apply(this, args);
  3397. };
  3398. _$_map.set(_is, _res.is);
  3399. }
  3400. return _res;
  3401. }
  3402. });
  3403. _$_map.set(x, _$[name]);
  3404. return true;
  3405. }
  3406. };
  3407. };
  3408. Object.defineProperty(win, '$', getJQWrap('$'));
  3409. Object.defineProperty(win, 'jQuery', getJQWrap('jQuery'));
  3410. let _dP = Object.defineProperty;
  3411. Object.defineProperty = function (...args) {
  3412. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery'))
  3413. return undefined;
  3414. return _dP.apply(this, args);
  3415. };
  3416. })
  3417. },
  3418.  
  3419. 'igra-prestoloff.cx': () => scriptLander(() => {
  3420. /*jslint evil: true */ // yes, evil, I know
  3421. let _write = _document.write.bind(_document);
  3422. /*jslint evil: false */
  3423. nt.define('document.write', t => {
  3424. let id = t.match(/jwplayer\("(\w+)"\)/i);
  3425. if (id && id[1])
  3426. return _write(`<div id="${id[1]}"></div>${t}`);
  3427. return _write('');
  3428. }, {
  3429. enumerable: true
  3430. });
  3431. }),
  3432.  
  3433. 'imageban.ru': () => {
  3434. Object.defineProperty(win, 'V7x1J', {
  3435. get() {
  3436. return null;
  3437. }
  3438. });
  3439. },
  3440.  
  3441. 'inoreader.com': () => scriptLander(() => {
  3442. let i = setInterval(() => {
  3443. if ('adb_detected' in win) {
  3444. win.adb_detected = () => win.adb_not_detected();
  3445. clearInterval(i);
  3446. }
  3447. }, 10);
  3448. _document.addEventListener('DOMContentLoaded', () => clearInterval(i), false);
  3449. }),
  3450.  
  3451. 'it-actual.ru': () => scriptLander(() => {
  3452. abortExecution.onAll('blocked');
  3453. abortExecution.onGet('nsg');
  3454. }, abortExecution),
  3455.  
  3456. 'ivi.ru': () => {
  3457. let _xhr_open = win.XMLHttpRequest.prototype.open;
  3458. win.XMLHttpRequest.prototype.open = function (method, url, ...args) {
  3459. if (typeof url === 'string')
  3460. if (url.endsWith('/track'))
  3461. return;
  3462. return _xhr_open.call(this, method, url, ...args);
  3463. };
  3464. let _responseText = Object.getOwnPropertyDescriptor(XMLHttpRequest.prototype, 'responseText');
  3465. let _responseText_get = _responseText.get;
  3466. _responseText.get = function () {
  3467. if (this.__responseText__)
  3468. return this.__responseText__;
  3469. let res = _responseText_get.apply(this, arguments);
  3470. let o;
  3471. try {
  3472. if (res)
  3473. o = JSON.parse(res);
  3474. } catch (ignore) {}
  3475. let changed = false;
  3476. if (o && o.result) {
  3477. if (o.result instanceof Array &&
  3478. 'adv_network_logo_url' in o.result[0]) {
  3479. o.result = [];
  3480. changed = true;
  3481. }
  3482. if (o.result.show_adv) {
  3483. o.result.show_adv = false;
  3484. changed = true;
  3485. }
  3486. }
  3487. if (changed) {
  3488. _console.log('changed response >>', o);
  3489. res = JSON.stringify(o);
  3490. }
  3491. this.__responseText__ = res;
  3492. return res;
  3493. };
  3494. Object.defineProperty(XMLHttpRequest.prototype, 'responseText', _responseText);
  3495. },
  3496.  
  3497. 'kakprosto.ru': () => scriptLander(() => {
  3498. selectiveCookies('yadb');
  3499. abortExecution.inlineScript('yaProxy', {
  3500. pattern: /yadb/
  3501. });
  3502. abortExecution.inlineScript('yandexContextAsyncCallbacks');
  3503. abortExecution.inlineScript('adfoxAsyncParams');
  3504. abortExecution.inlineScript('adfoxBackGroundLoaded');
  3505. }, selectiveCookies, abortExecution),
  3506.  
  3507. 'kinopoisk.ru': () => {
  3508. // filter cookies
  3509. // set no-branding body style and adjust other blocks on the page
  3510. const style = {
  3511. '.app__header.app__header_margin-bottom_brand, #top': {
  3512. margin_bottom: '20px !important'
  3513. },
  3514. '.app__branding': {
  3515. display: 'none!important'
  3516. }
  3517. };
  3518. if (location.hostname === 'www.kinopoisk.ru' && !location.pathname.startsWith('/games/'))
  3519. style['html:not(#id), body:not(#id), .app-container'] = {
  3520. background: '#d5d5d5 url(/images/noBrandBg.jpg) 50% 0 no-repeat !important'
  3521. };
  3522. createStyle(style);
  3523. scriptLander(() => {
  3524. selectiveCookies('cmtchd|crookie|kpunk');
  3525. // filter JSON
  3526. win.JSON.parse = new Proxy(win.JSON.parse, {
  3527. apply(fun, that, args) {
  3528. let o = _apply(fun, that, args);
  3529. let name = 'antiAdBlockCookieName';
  3530. if (name in o && typeof o[name] === 'string')
  3531. selectiveCookies(o[name]);
  3532. name = 'branding';
  3533. if (name in o) o[name] = {};
  3534. // tricks against ads in the trailer player
  3535. // if (location.hostname.startsWith('widgets.'))
  3536. if (o.page && o.page.playerParams)
  3537. delete o.page.playerParams.adConfig;
  3538. if (o.common && o.common.bunker && o.common.bunker.adv && o.common.bunker.adv.filmIdWithoutAd)
  3539. o.common.bunker.adv.filmIdWithoutAd.includes = () => true;
  3540. //_console.log('JSON.parse', o);
  3541. return o;
  3542. }
  3543. });
  3544. // skip timeout check for blocked requests
  3545. win.setTimeout = new Proxy(win.setTimeout, {
  3546. apply(fun, that, args) {
  3547. if (args[1] === 100) {
  3548. let str = _toString(args[0]);
  3549. if (str.endsWith('{a()}') || str.endsWith('{n()}'))
  3550. return;
  3551. }
  3552. return _apply(fun, that, args);
  3553. }
  3554. });
  3555. // obfuscated Yandex.Direct
  3556. nt.define('Object.prototype.initYaDirect', undefined);
  3557. nt.define('Object.prototype._resolveDetectResult', () => null);
  3558. nt.define('Object.prototype.detectResultPromise', new Promise(r => r(false)));
  3559. if (location.hostname === 'www.kinopoisk.ru')
  3560. nt.define('Object.prototype.initAd', nt.func(undefined, 'initAd'));
  3561. // catch branding and other things
  3562. let _KP;
  3563. Object.defineProperty(win, 'KP', {
  3564. get() {
  3565. return _KP;
  3566. },
  3567. set(val) {
  3568. if (_KP === val)
  3569. return true;
  3570. _KP = new Proxy(val, {
  3571. set(kp, name, val) {
  3572. if (name === 'branding') {
  3573. kp[name] = new Proxy({
  3574. weborama: {}
  3575. }, {
  3576. get(kp, name) {
  3577. return name in kp ? kp[name] : '';
  3578. },
  3579. set() {}
  3580. });
  3581. return true;
  3582. }
  3583. if (name === 'config')
  3584. val = new Proxy(val, {
  3585. set(cfg, name, val) {
  3586. if (name === 'anContextUrl')
  3587. return true;
  3588. if (name === 'adfoxEnabled' || name === 'hasBranding')
  3589. val = false;
  3590. if (name === 'adfoxVideoAdUrls')
  3591. val = {
  3592. flash: {},
  3593. html: {}
  3594. };
  3595. cfg[name] = val;
  3596. return true;
  3597. }
  3598. });
  3599. kp[name] = val;
  3600. return true;
  3601. }
  3602. });
  3603. _console.log('KP =', val);
  3604. }
  3605. });
  3606. }, selectiveCookies, nullTools);
  3607. },
  3608.  
  3609. 'korrespondent.net': {
  3610. now: () => scriptLander(() => {
  3611. nt.define('holder', function (id) {
  3612. let div = _document.getElementById(id);
  3613. if (!div)
  3614. return;
  3615. if (div.parentNode.classList.contains('col__sidebar')) {
  3616. div.parentNode.appendChild(div);
  3617. div.style.height = '300px';
  3618. }
  3619. });
  3620. }, nullTools),
  3621. dom() {
  3622. for (let frame of _document.querySelectorAll('.unit-side-informer > iframe'))
  3623. frame.parentNode.style.width = '1px';
  3624. }
  3625. },
  3626.  
  3627. 'libertycity.ru': () => scriptLander(() => {
  3628. nt.define('adBlockEnabled', false);
  3629. }, nullTools),
  3630.  
  3631. 'liveinternet.ru': () => scriptLander(() => {
  3632. abortExecution.onGet('Object.prototype.initAd');
  3633. }, abortExecution),
  3634.  
  3635. 'livejournal.com': () => scriptLander(() => {
  3636. nt.define('Object.prototype.Adf', undefined);
  3637. nt.define('Object.prototype.Begun', undefined);
  3638. }, nullTools),
  3639.  
  3640. 'mail.ru': {
  3641. other: 'ok.ru, sportmail.ru',
  3642. now: () => scriptLander(() => {
  3643. const _hostparts = location.hostname.split('.');
  3644. const _subdomain = _hostparts.slice(-3).join('.');
  3645. const _hostname = _hostparts.slice(-2).join('.');
  3646. const _emailru = _subdomain === 'e.mail.ru' || _subdomain === 'octavius.mail.ru';
  3647. const _mymailru = _subdomain === 'my.mail.ru';
  3648. const _okru = _hostname === 'ok.ru';
  3649. // setTimeout filter
  3650. // advBlock|rbParams - ads
  3651. // document\.title= - blinking title on background news load on main page
  3652. const pattern = /advBlock|rbParams|document\.title=/i;
  3653. const _setTimeout = win.setTimeout;
  3654. win.setTimeout = function setTimeout(...args) {
  3655. let text = _toString(args[0]);
  3656. if (pattern.test(text)) {
  3657. _console.trace('Skipped setTimeout:', text);
  3658. return;
  3659. }
  3660. return _setTimeout(...args);
  3661. };
  3662.  
  3663. // Trick to prevent mail.ru from removing 3rd-party styles
  3664. nt.define('Object.prototype.restoreVisibility', nt.func(null, 'restoreVisibility'));
  3665. // Other Yandex Direct and other ads
  3666. nt.define('Object.prototype.initMimic', undefined);
  3667. nt.define('Object.prototype.hpConfig', undefined);
  3668. nt.define('Object.prototype.direct', undefined);
  3669. const getAds = () => new Promise(
  3670. r => r(nt.proxy({}, '?.getAds()'))
  3671. );
  3672. nt.define('Object.prototype.getAds', getAds);
  3673. nt.define('rb_counter', nt.func(null, 'rb_counter'));
  3674. if (_subdomain === 'mail.ru') { // main page
  3675. nt.define('Object.prototype.baits', undefined); // detector
  3676. nt.define('Object.prototype.getFeed', nt.func(null, 'pulse.getFeed')); // Pulse feed
  3677. createStyle('body > div > .pulse { display: none !important }');
  3678. }
  3679. if (_emailru)
  3680. nt.define('Object.prototype.show_me_ads', undefined);
  3681. else if (_mymailru)
  3682. nt.define('Object.prototype.runMimic', nt.func(null, 'runMimic'));
  3683. else {
  3684. nt.define('Object.prototype.mimic', undefined);
  3685. const xray = nt.func(undefined, 'xray');
  3686. nt.defineOn(xray, 'send', nt.func(undefined, 'xray.send'), 'xray.');
  3687. nt.defineOn(xray, 'radarPrefix', null, 'xray.');
  3688. nt.defineOn(xray, 'xrayRadarUrl', undefined, 'xray.');
  3689. nt.defineOn(xray, 'defaultParams', nt.proxy({
  3690. i: undefined,
  3691. p: 'media'
  3692. }), 'xray.');
  3693. nt.define('Object.prototype.xray', nt.proxy(xray));
  3694. }
  3695. // shenanigans against ok.ru ABP detector
  3696. if (_okru) {
  3697. abortExecution.onGet('OK.hooks');
  3698. // banners on ok.ru and counter
  3699. nt.define('getAdvTargetParam', nt.func(null, 'getAdvTargetParam'));
  3700. // break detection in case detector wasn't wrapped
  3701. abortExecution.onSet('Object.prototype.adBlockDetected');
  3702. }
  3703. // news.mail.ru and sportmail.ru
  3704. abortExecution.onGet('myWidget');
  3705. // cleanup e.mail.ru configs and mimic config on news and sport
  3706. const emptyString = (root, name) => root[name] && (root[name] = '');
  3707. const detectMimic = /direct|240x400|SlotView/;
  3708. win.JSON.parse = new Proxy(win.JSON.parse, {
  3709. apply(fun, that, args) {
  3710. let o = _apply(fun, that, args);
  3711. if (o && typeof o === 'object') {
  3712. if (o.cfg && o.cfg.sotaFeatures) {
  3713. let root = o.cfg.sotaFeatures;
  3714. if (Array.isArray(root.adv)) root.adv = [];
  3715. for (let name in root)
  3716. if (name.startsWith('adv-') || name.startsWith('adman-'))
  3717. delete root[name];
  3718. ['email_logs_to', 'smokescreen-locators'].forEach(name => emptyString(root, name));
  3719. }
  3720. if (o.userConfig) {
  3721. if (Array.isArray(o.userConfig.honeypot))
  3722. o.userConfig.honeypot.forEach((v, id, me) => (me[id] = []));
  3723. const cfg = o.userConfig.config;
  3724. if (cfg && cfg.honeypot)
  3725. emptyString(cfg.honeypot, 'baits');
  3726. }
  3727. if (o.body) {
  3728. const flags = o.body.common_purpose_flags;
  3729. if (flags && 'hide_ad_in_mail_web' in flags)
  3730. flags.hide_ad_in_mail_web = true;
  3731. if (o.body.show_me_ads)
  3732. o.body.show_me_ads = false;
  3733. }
  3734. //_console.log('JSON.parse', o);
  3735. }
  3736. if (Array.isArray(o))
  3737. if (o.some(t => typeof t === 'string' && detectMimic.test(t))) {
  3738. _console.log('Replaced', o);
  3739. o = [];
  3740. } //else _console.log('JSON.parse', o);
  3741. return o;
  3742. }
  3743. });
  3744. // all the rest is only needed on main page and in emails
  3745. if (_subdomain !== 'mail.ru' && !_emailru && !_okru)
  3746. return;
  3747.  
  3748. // Disable page scrambler on mail.ru to let extensions easily block ads there
  3749. let logger = {
  3750. apply(fun, that, args) {
  3751. let res = _apply(fun, that, args);
  3752. _console.log(`${fun._name}(`, ...args, `)\n>>`, res);
  3753. return res;
  3754. }
  3755. };
  3756.  
  3757. function wrapLocator(locator) {
  3758. if ('setup' in locator) {
  3759. let _setup = locator.setup;
  3760. locator.setup = function (o) {
  3761. if ('enable' in o) {
  3762. o.enable = false;
  3763. _console.log('Disable mimic mode.');
  3764. }
  3765. if ('links' in o) {
  3766. o.links = [];
  3767. _console.log('Call with empty list of sheets.');
  3768. }
  3769. return _setup.call(this, o);
  3770. };
  3771. locator.insertSheet = () => false;
  3772. locator.wrap = () => false;
  3773. }
  3774. try {
  3775. let names = [];
  3776. for (let name in locator)
  3777. if (typeof locator[name] === 'function' && name !== 'transform') {
  3778. locator[name]._name = "locator." + name;
  3779. locator[name] = new Proxy(locator[name], logger);
  3780. names.push(name);
  3781. }
  3782. _console.log(`[locator] wrapped properties: ${names.length ? names.join(', ') : '[empty]'}`);
  3783. } catch (e) {
  3784. _console.log(e);
  3785. }
  3786. return locator;
  3787. }
  3788.  
  3789. function defineLocator(root) {
  3790. let _locator = root.locator;
  3791. let wrapLocatorSetter = vl => _locator = wrapLocator(vl);
  3792. let loc_desc = Object.getOwnPropertyDescriptor(root, 'locator');
  3793. if (!loc_desc || loc_desc.set !== wrapLocatorSetter)
  3794. try {
  3795. Object.defineProperty(root, 'locator', {
  3796. set: wrapLocatorSetter,
  3797. get() {
  3798. return _locator;
  3799. }
  3800. });
  3801. } catch (err) {
  3802. _console.log('Unable to redefine "locator" object!!!', err);
  3803. }
  3804. if (loc_desc.value)
  3805. _locator = wrapLocator(loc_desc.value);
  3806. }
  3807.  
  3808. { // auto-stubs for various ad, detection and obfuscation modules
  3809. const missingCheck = {
  3810. get(obj, name) {
  3811. let res = obj[name];
  3812. if (!(name in obj))
  3813. _console.trace(`Missing "${name}" in`, obj);
  3814. return res;
  3815. }
  3816. };
  3817. const skipLog = (name, ret) => (...args) => (_console.log(`${name}(`, ...args, ')'), ret);
  3818. const createSkipAllObject = (baseName, obj = {
  3819. __esModule: true
  3820. }) => new Proxy(obj, {
  3821. get(obj, name) {
  3822. if (name in obj)
  3823. return obj[name];
  3824. _console.log(`Created stub for "${name}" in ${baseName}.`);
  3825. obj[name] = skipLog(`${baseName}.${name}`);
  3826. return obj[name];
  3827. },
  3828. set() {}
  3829. });
  3830. const redefiner = {
  3831. apply(fun, that, args) {
  3832. let res;
  3833. let warn = false;
  3834. let name = fun._name;
  3835. if (name === 'mrg-smokescreen/Welter')
  3836. res = {
  3837. isWelter() {
  3838. return true;
  3839. },
  3840. wrap: skipLog(`${name}.wrap`)
  3841. };
  3842. if (name === 'mrg-smokescreen/Honeypot')
  3843. res = {
  3844. check(...args) {
  3845. _console.log(`${name}.check(`, ...args, ')');
  3846. return new Promise(() => undefined);
  3847. },
  3848. version: "-1"
  3849. };
  3850. if (name === 'advert/adman/adman') {
  3851. let features = {
  3852. siteZones: {},
  3853. slots: {}
  3854. };
  3855. [
  3856. 'expId', 'siteId', 'mimicEndpoint', 'mimicPartnerId',
  3857. 'immediateFetchTimeout', 'delayedFetchTimeout'
  3858. ].forEach(name => void(features[name] = null));
  3859. res = createSkipAllObject(name, {
  3860. getFeatures: skipLog(`${name}.getFeatures`, features)
  3861. });
  3862. }
  3863. if (name === 'mrg-smokescreen/Utils')
  3864. res = createSkipAllObject(name, {
  3865. extend(...args) {
  3866. let res = {
  3867. enable: false,
  3868. match: [],
  3869. links: []
  3870. };
  3871. _console.log(`${name}.extend(`, ...args, ') >>', res);
  3872. return res;
  3873. }
  3874. });
  3875. if (name.startsWith('OK/banners/') ||
  3876. name.startsWith('mrg-smokescreen/StyleSheets') ||
  3877. name === '@mail/mimic' ||
  3878. name === 'mediator/advert-managers')
  3879. res = createSkipAllObject(name);
  3880. if (res) {
  3881. Object.defineProperty(res, Symbol.toStringTag, {
  3882. get() {
  3883. return `Skiplog object for ${name}`;
  3884. }
  3885. });
  3886. Object.defineProperty(res, Symbol.toPrimitive, {
  3887. value(hint) {
  3888. if (hint === 'string')
  3889. return Object.prototype.toString.call(this);
  3890. return `[missing toPrimitive] ${name} ${hint}`;
  3891. }
  3892. });
  3893. res = new Proxy(res, missingCheck);
  3894. } else {
  3895. res = _apply(fun, that, args);
  3896. warn = true;
  3897. }
  3898. _console[warn ? 'warn' : 'log'](name, '(', ...args, ')\n>>', res);
  3899. return res;
  3900. }
  3901. };
  3902.  
  3903. const advModuleNamesStartWith = /^(mrg-(context|honeypot)|adv\/)/;
  3904. const advModuleNamesGeneric = /advert|banner|mimic|smoke/i;
  3905. const wrapAdFuncs = {
  3906. apply(fun, that, args) {
  3907. let module = args[0];
  3908. if (typeof module === 'string')
  3909. if ((advModuleNamesStartWith.test(module) ||
  3910. advModuleNamesGeneric.test(module)) &&
  3911. // fix for e.mail.ru in Fx56 and below, looks like Proxy is quirky there
  3912. !module.startsWith('patron.v2.')) {
  3913. let main = args[args.length - 1];
  3914. main._name = module;
  3915. args[args.length - 1] = new Proxy(main, redefiner);
  3916. }
  3917. return _apply(fun, that, args);
  3918. }
  3919. };
  3920. const wrapDefine = def => {
  3921. if (!def)
  3922. return;
  3923. _console.log('define =', def);
  3924. def = new Proxy(def, wrapAdFuncs);
  3925. def._name = 'define';
  3926. return def;
  3927. };
  3928. let _define = wrapDefine(win.define);
  3929. Object.defineProperty(win, 'define', {
  3930. get() {
  3931. return _define;
  3932. },
  3933. set(x) {
  3934. if (_define === x)
  3935. return true;
  3936. _define = wrapDefine(x);
  3937. return true;
  3938. }
  3939. });
  3940. }
  3941.  
  3942. let _honeyPot;
  3943.  
  3944. function defineDetector(mr) {
  3945. let __ = mr._ || {};
  3946. let setHoneyPot = o => {
  3947. if (!o || o === _honeyPot) return;
  3948. _console.log('[honeyPot]', o);
  3949. _honeyPot = function () {
  3950. this.check = new Proxy(() => {
  3951. __.STUCK_IN_POT = false;
  3952. return false;
  3953. }, logger);
  3954. this.check._name = 'honeyPot.check';
  3955. this.destroy = () => null;
  3956. };
  3957. };
  3958. if ('honeyPot' in mr)
  3959. setHoneyPot(mr.honeyPot);
  3960. else
  3961. Object.defineProperty(mr, 'honeyPot', {
  3962. get() {
  3963. return _honeyPot;
  3964. },
  3965. set: setHoneyPot
  3966. });
  3967.  
  3968. __ = new Proxy(__, {
  3969. get(target, prop) {
  3970. return target[prop];
  3971. },
  3972. set(target, prop, val) {
  3973. _console.log(`mr._.${prop} =`, val);
  3974. target[prop] = val;
  3975. return true;
  3976. }
  3977. });
  3978. mr._ = __;
  3979. }
  3980.  
  3981. function defineAdd(mr) {
  3982. let _add;
  3983. let addWrapper = {
  3984. apply(fun, that, args) {
  3985. let module = args[0];
  3986. if (typeof module === 'string' && module.startsWith('ad')) {
  3987. _console.log('Skip module:', module);
  3988. return;
  3989. }
  3990. if (typeof module === 'object' && module.name.startsWith('ad'))
  3991. _console.log('Loaded module:', module);
  3992. return logger.apply(fun, that, args);
  3993. }
  3994. };
  3995. let setMrAdd = v => {
  3996. if (!v) return;
  3997. v._name = 'mr.add';
  3998. v = new Proxy(v, addWrapper);
  3999. _add = v;
  4000. };
  4001. if ('add' in mr)
  4002. setMrAdd(mr.add);
  4003. Object.defineProperty(mr, 'add', {
  4004. get() {
  4005. return _add;
  4006. },
  4007. set: setMrAdd
  4008. });
  4009.  
  4010. }
  4011.  
  4012. const _mr_wrapper = vl => {
  4013. defineLocator(vl.mimic ? vl.mimic : vl);
  4014. defineDetector(vl);
  4015. defineAdd(vl);
  4016. return vl;
  4017. };
  4018. if ('mr' in win) {
  4019. _console.log('Found existing "mr" object.');
  4020. win.mr = _mr_wrapper(win.mr);
  4021. } else {
  4022. let _mr;
  4023. Object.defineProperty(win, 'mr', {
  4024. get() {
  4025. return _mr;
  4026. },
  4027. set(vl) {
  4028. _mr = vl ? _mr_wrapper(vl) : vl;
  4029. },
  4030. configurable: true
  4031. });
  4032. let _defineProperty = _bindCall(Object.defineProperty);
  4033. Object.defineProperty = function defineProperty(...args) {
  4034. const [obj, name, conf] = args;
  4035. if (name === 'mr' && obj instanceof Window) {
  4036. _console.trace('Object.defineProperty(', ...args, ')');
  4037. conf.set(_mr_wrapper(conf.get()));
  4038. }
  4039. if ((name === 'honeyPot' || name === 'add') && _mr === obj && conf.set)
  4040. return;
  4041. return _defineProperty(this, ...args);
  4042. };
  4043. }
  4044. }, nullTools, selectiveCookies, abortExecution)
  4045. },
  4046.  
  4047. 'oms.matchat.online': () => scriptLander(() => {
  4048. let _rmpGlobals;
  4049. Object.defineProperty(win, 'rmpGlobals', {
  4050. get() {
  4051. return _rmpGlobals;
  4052. },
  4053. set(val) {
  4054. if (val === _rmpGlobals)
  4055. return true;
  4056. _rmpGlobals = new Proxy(val, {
  4057. get(obj, name) {
  4058. if (name === 'adBlockerDetected')
  4059. return false;
  4060. return obj[name];
  4061. },
  4062. set(obj, name, val) {
  4063. if (name === 'adBlockerDetected')
  4064. _console.trace('rmpGlobals.adBlockerDetected =', val);
  4065. else
  4066. obj[name] = val;
  4067. return true;
  4068. }
  4069. });
  4070. }
  4071. });
  4072. }),
  4073.  
  4074. 'megogo.net': {
  4075. now() {
  4076. nt.define('adBlock', false);
  4077. nt.define('showAdBlockMessage', nt.func(null, 'showAdBlockMessage'));
  4078. }
  4079. },
  4080.  
  4081. 'naruto-base.su': () => gardener('div[id^="entryID"],.block', /href="http.*?target="_blank"/i),
  4082.  
  4083. 'otzovik.com': () => scriptLander(() => {
  4084. abortExecution.onGet('Object.prototype.DirectManagerStart');
  4085. abortExecution.onGet('Object.prototype._visibilityConfirmer');
  4086. let _o_math = win.o_math;
  4087. Object.defineProperty(win, 'o_math', {
  4088. get() {
  4089. return _o_math;
  4090. },
  4091. set(val) {
  4092. delete val.ext_uid;
  4093. _o_math = val;
  4094. }
  4095. });
  4096. }, abortExecution, selectiveCookies),
  4097.  
  4098. 'overclockers.ru': {
  4099. now() {
  4100. abortExecution.onAll('cardinals');
  4101. abortExecution.inlineScript('Document.prototype.createElement', {
  4102. pattern: /mamydirect/
  4103. });
  4104. }
  4105. },
  4106.  
  4107. 'peka2.tv': () => {
  4108. let bodyClass = 'body--branding';
  4109. let checkNode = node => {
  4110. for (let className of node.classList)
  4111. if (className.includes('banner') || className === bodyClass) {
  4112. _removeAttribute(node, 'style');
  4113. node.classList.remove(className);
  4114. for (let attr of Array.from(node.attributes))
  4115. if (attr.name.startsWith('advert'))
  4116. _removeAttribute(node, attr.name);
  4117. }
  4118. };
  4119. (new MutationObserver(ms => {
  4120. let m, node;
  4121. for (m of ms)
  4122. for (node of m.addedNodes)
  4123. if (node instanceof HTMLElement)
  4124. checkNode(node);
  4125. })).observe(_de, {
  4126. childList: true,
  4127. subtree: true
  4128. });
  4129. (new MutationObserver(ms => {
  4130. for (let m of ms)
  4131. checkNode(m.target);
  4132. })).observe(_de, {
  4133. attributes: true,
  4134. subtree: true,
  4135. attributeFilter: ['class']
  4136. });
  4137. },
  4138.  
  4139. 'pikabu.ru': () => gardener('.story', /story__author[^>]+>ads</i, {
  4140. root: '.inner_wrap',
  4141. observe: true
  4142. }),
  4143.  
  4144. 'piratbit.tld': {
  4145. other: 'pb.wtf',
  4146. dom() {
  4147. const remove = node => node && node.parentNode && (_console.log('removed', node), node.parentNode.removeChild(node));
  4148. const isAdLink = el => location.hostname === el.hostname && /^\/(\w{3}|exit|out)\/[\w=/]{20,}$/.test(el.pathname);
  4149. // line above topic content and images in the slider in the header
  4150. for (let el of _document.querySelectorAll('.releas-navbar div a, #page_contents a'))
  4151. if (isAdLink(el))
  4152. remove(el.closest('tr[class]:not(.top_line):not(.active), .row2[id^="post_"]') || el.closest('div[style]:not(.row1):not(.btn-group)'));
  4153. }
  4154. },
  4155.  
  4156. 'pixelexperience.org': () => scriptLander(() => {
  4157. abortExecution.inlineScript('eval', {
  4158. pattern: /blockadblock/
  4159. });
  4160. }, abortExecution),
  4161.  
  4162. 'player.starlight.digital': {
  4163. other: 'teleportal.ua',
  4164. dom() {
  4165. scriptLander(() => {
  4166. let _currVideo = win.currVideo;
  4167. Object.defineProperty(win, 'currVideo', {
  4168. get() {
  4169. return _currVideo;
  4170. },
  4171. set(val) {
  4172. _console.log('currVideo =', val);
  4173. if ('adv' in val)
  4174. val.adv.creatives = [];
  4175. if ('showadv' in val)
  4176. val.showadv = false;
  4177. if ('mediaHls' in val)
  4178. val.mediaHls = val.mediaHls.replace('adv=1', 'adv=0');
  4179. if ('media' in val)
  4180. for (let media of val.media)
  4181. media.url = media.url.replace('adv=1', 'adv=0');
  4182. _currVideo = val;
  4183. }
  4184. });
  4185. nt.define('Object.prototype.isAdBlockEnabled', false);
  4186. nt.define('Object.prototype.AdBlockDynamicConfig', undefined);
  4187. nt.define('ADT_PLAYER_ADBLOCK_CONFIG', '');
  4188. nt.define('ADT_PLAYER_ADBLOCK_CONFIG_DETECT_ON_FAIL', false);
  4189. }, nullTools);
  4190. }
  4191. },
  4192.  
  4193. 'qrz.ru': {
  4194. now() {
  4195. nt.define('ab', false);
  4196. nt.define('tryMessage', nt.func(null, 'tryMessage'));
  4197. }
  4198. },
  4199.  
  4200. 'rambler.ru': {
  4201. other: [
  4202. 'autorambler.ru', 'championat.com', 'eda.ru', 'gazeta.ru', 'lenta.ru', 'letidor.ru',
  4203. 'media.eagleplatform.com', 'motor.ru', 'passion.ru', 'quto.ru', 'rns.online', 'wmj.ru'
  4204. ].join(','),
  4205. now() {
  4206. scriptLander(() => {
  4207. // Skip login form and frames, and comments frames. Nothing to do here.
  4208. if (['id.rambler.ru', 'comments.rambler.ru'].includes(location.hostname))
  4209. return;
  4210.  
  4211. // prevent autoplay
  4212. if (location.hostname === 'vp.rambler.ru') {
  4213. nt.define('Object.prototype.VIEWPORT_VISIBLE_AREA_CHANGED', () => false);
  4214. return;
  4215. }
  4216. if (location.hostname.endsWith('.media.eagleplatform.com')) {
  4217. const _stopImmediatePropagation = _bindCall(Event.prototype.stopImmediatePropagation);
  4218. win.addEventListener('message', e => {
  4219. if (typeof e.data === 'object' && e.data.visible)
  4220. _stopImmediatePropagation(e);
  4221. });
  4222. return;
  4223. }
  4224. /* jshint -W001 */ // aka 'hasOwnProperty' is a really bad name, but this is a wrapper
  4225. const autoList = new Set(['autoplay', 'scrollplay']);
  4226. win.Object.prototype.hasOwnProperty = new Proxy(win.Object.prototype.hasOwnProperty, {
  4227. apply(fun, that, args) {
  4228. if (autoList.has(args[0]))
  4229. return false;
  4230. return _apply(fun, that, args);
  4231. }
  4232. });
  4233. /* jshint +W001 */
  4234.  
  4235. selectiveCookies('detect_count|dv|dvr|lv|lvr');
  4236. // Wrapper for adv loader settings in QW50aS1BZEJsb2Nr['7t7hystz']
  4237. const _contexts = new WeakMap();
  4238. Object.defineProperty(Object.prototype, 'Settings', {
  4239. set(val) {
  4240. if (typeof val === 'object' && 'Transports' in val && 'Urls' in val)
  4241. val.Urls = [];
  4242. _contexts.set(this, val);
  4243. },
  4244. get() {
  4245. return _contexts.get(this);
  4246. }
  4247. });
  4248. // disable video pop-outs in articles on gazeta.ru
  4249. if (location.hostname === 'gazeta.ru' || location.hostname.endsWith('.gazeta.ru'))
  4250. nt.define('creepyVideo', nt.func(null, 'creepyVideo'));
  4251. // disable Alice popup (encountered on horoscopes.rambler.ru)
  4252. nt.define('Object.prototype.needShowAlicePopup', false);
  4253. // disable some logging
  4254. yandexRavenStub();
  4255. // hide "disable ads" button
  4256. createStyle('a[href^="https://prime.rambler.ru/promo/"] { display: none !important }');
  4257. // prevent ads from loading
  4258. abortExecution.onGet('g_GazetaNoExchange');
  4259.  
  4260. //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;
  4261. const scriptSkipList = /nrWrapper|\/(desktopVendor|vendorsDesktop)\.|<anonymous>/;
  4262. const isLocalScript = (log) => {
  4263. let e = removeOwnFootprint(new Error()),
  4264. parts = e.stack.split(/\n/),
  4265. row = 0;
  4266. if (!/http/.test(parts[row]))
  4267. row += 1;
  4268. while (scriptSkipList.test(parts[row]))
  4269. row += 1;
  4270. let parse = /(https?:.*):\d+:\d+/.exec(parts[row]);
  4271. if (log)
  4272. _console.log(parse && parse[1] === location.href, parts[row], [parts]);
  4273. return parse && parse[1] === location.href;
  4274. };
  4275. const cutoff = 200;
  4276. const fts = f => _toString(f.__sentry__ && f.__sentry_original__ || f['nr@original'] || f);
  4277. win.setTimeout = new Proxy(win.setTimeout, {
  4278. apply(fun, that, args) {
  4279. if (isLocalScript()) {
  4280. const [callback, delay] = args;
  4281. const str = fts(callback);
  4282. if (!/\n/.test(str)) {
  4283. _console.trace(`Skipped setTimeout(${str.slice(0, cutoff)}${str.length > cutoff ? '\u2026' : ''}, ${delay})`);
  4284. return null;
  4285. }
  4286. }
  4287. return _apply(fun, that, args);
  4288. }
  4289. });
  4290. const _onerror = Object.getOwnPropertyDescriptor(win.HTMLElement.prototype, 'onerror');
  4291. _onerror.set = new Proxy(_onerror.set, {
  4292. apply(fun, that, args) {
  4293. if (typeof args[0] === 'function' && isLocalScript()) {
  4294. const str = fts(args[0]);
  4295. _console.trace(`Skipped onerror = ${str.slice(0, cutoff)}${str.length > cutoff ? '\u2026' : ''}`);
  4296. return;
  4297. }
  4298. return _apply(fun, that, args);
  4299. }
  4300. });
  4301. Object.defineProperty(win.HTMLElement.prototype, 'onerror', _onerror);
  4302. // Skip dev console check
  4303. win.console.debug = new Proxy(win.console.debug, {
  4304. apply(fun, that, args) {
  4305. if (args[0] instanceof HTMLImageElement)
  4306. return;
  4307. return _apply(fun, that, args);
  4308. }
  4309. });
  4310. // anti-abdetector
  4311. let _primeStorage;
  4312. Object.defineProperty(win, 'primeStorage', {
  4313. get() {
  4314. if (isLocalScript())
  4315. throw removeOwnFootprint(new TypeError(`Cannot read property 'primeStorage' of undefined`));
  4316. return _primeStorage;
  4317. },
  4318. set(val) {
  4319. _primeStorage = val;
  4320. }
  4321. });
  4322. // Defense against triggered detector
  4323. _Node.removeChild = new Proxy(_Node.removeChild, {
  4324. apply(fun, that, args) {
  4325. const [el] = args;
  4326. if (el.tagName === 'LINK' && isLocalScript()) {
  4327. _console.log(`Let's not remove ${el.tagName}.`);
  4328. return;
  4329. }
  4330. return _apply(fun, that, args);
  4331. }
  4332. });
  4333. }, nullTools, yandexRavenStub, selectiveCookies, abortExecution);
  4334. },
  4335. dom() {
  4336. // disable video pop-outs in articles on lenta.ru and rambler.ru
  4337. let domain = location.hostname.split('.');
  4338. if (['lenta', 'rambler'].includes(domain[domain.length - 2])) {
  4339. const player = _document.querySelector('.js-video-box__container, .j-mini-player__video');
  4340. if (player) player.removeAttribute('class');
  4341. }
  4342. // remove utm_ form links
  4343. const parser = _document.createElement('a');
  4344. _document.addEventListener('mousedown', (e) => {
  4345. let t = e.target;
  4346. if (!t.href)
  4347. t = t.closest('A');
  4348. if (t && t.href) {
  4349. parser.href = t.href;
  4350. let remove = [];
  4351. let params = parser.search.slice(1).split('&').filter(name => {
  4352. if (name.startsWith('utm_')) {
  4353. remove.push(name);
  4354. return false;
  4355. }
  4356. return true;
  4357. });
  4358. if (remove.length)
  4359. _console.log('Removed parameters from link:', ...remove);
  4360. if (params.length)
  4361. parser.search = `?${params.join('&')}`;
  4362. else
  4363. parser.search = '';
  4364. t.href = parser.href;
  4365. }
  4366. }, false);
  4367. }
  4368. },
  4369.  
  4370. 'razlozhi.ru': {
  4371. now() {
  4372. nt.define('cadb', false);
  4373. for (let func of ['createShadowRoot', 'attachShadow'])
  4374. if (func in _Element)
  4375. _Element[func] = function () {
  4376. return this.cloneNode();
  4377. };
  4378. }
  4379. },
  4380.  
  4381. 'rbc.ru': {
  4382. other: 'autonews.ru, rbcplus.ru, sportrbc.ru',
  4383. now() {
  4384. scriptLander(() => selectiveCookies('adb_on'), selectiveCookies);
  4385. let _RA;
  4386. let setArgs = {
  4387. 'showBanners': true,
  4388. 'showAds': true,
  4389. 'banners.staticPath': '',
  4390. 'paywall.staticPath': '',
  4391. 'banners.dfp.config': [],
  4392. 'banners.dfp.pageTargeting': () => null,
  4393. };
  4394. Object.defineProperty(win, 'RA', {
  4395. get() {
  4396. return _RA;
  4397. },
  4398. set(vl) {
  4399. _console.log('RA =', vl);
  4400. if ('repo' in vl) {
  4401. _console.log('RA.repo =', vl.repo);
  4402. vl.repo = new Proxy(vl.repo, {
  4403. set(obj, name, val) {
  4404. if (name === 'banner') {
  4405. _console.log(`RA.repo.${name} =`, val);
  4406. val = new Proxy(val, {
  4407. get(obj, name) {
  4408. let res = obj[name];
  4409. if (typeof obj[name] === 'function') {
  4410. res = () => undefined;
  4411. if (name === 'getService')
  4412. res = service => {
  4413. if (service === 'dfp')
  4414. return {
  4415. getPlaces() {
  4416. return;
  4417. },
  4418. createPlaceholder() {
  4419. return;
  4420. }
  4421. };
  4422. return undefined;
  4423. };
  4424. res.toString = obj[name].toString.bind(obj[name]);
  4425. }
  4426. if (name === 'isInited')
  4427. res = true;
  4428. _console.trace(`get RA.repo.banner.${name}`, res);
  4429. return res;
  4430. }
  4431. });
  4432. }
  4433. obj[name] = val;
  4434. return true;
  4435. }
  4436. });
  4437. } else
  4438. _console.log('Unable to locate RA.repo');
  4439. _RA = new Proxy(vl, {
  4440. set(o, name, val) {
  4441. if (name === 'config') {
  4442. _console.log('RA.config =', val);
  4443. if ('set' in val) {
  4444. val.set = new Proxy(val.set, {
  4445. apply(set, that, args) {
  4446. let name = args[0];
  4447. if (name in setArgs)
  4448. args[1] = setArgs[name];
  4449. if (name in setArgs || name === 'checkad')
  4450. _console.log('RA.config.set(', ...args, ')');
  4451. return _apply(set, that, args);
  4452. }
  4453. });
  4454. val.set('showAds', true); // pretend ads already were shown
  4455. }
  4456. }
  4457. o[name] = val;
  4458. return true;
  4459. }
  4460. });
  4461. }
  4462. });
  4463. Object.defineProperty(win, 'bannersConfig', {
  4464. set() {},
  4465. get() {
  4466. return [];
  4467. }
  4468. });
  4469. // pretend there is a paywall landing on screen already
  4470. let pwl = _document.createElement('div');
  4471. pwl.style.display = 'none';
  4472. pwl.className = 'js-paywall-landing';
  4473. _document.documentElement.appendChild(pwl);
  4474. // detect and skip execution of one of the ABP detectors
  4475. win.setTimeout = new Proxy(win.setTimeout, {
  4476. apply(fun, that, args) {
  4477. if (typeof args[0] === 'function') {
  4478. let fts = _toString(args[0]);
  4479. if (/\.length\s*>\s*0\s*&&/.test(fts) && /:hidden/.test(fts)) {
  4480. _console.log('Skipped setTimout(', fts, args[1], ')');
  4481. return;
  4482. }
  4483. }
  4484. return _apply(fun, that, args);
  4485. }
  4486. });
  4487. // hide banner placeholders
  4488. createStyle('[data-banner-id], .banner__container, .banners__yandex__article { display: none !important }');
  4489. },
  4490. dom() {
  4491. // hide sticky banner place at the top of the page
  4492. for (let itm of _document.querySelectorAll('.l-sticky'))
  4493. if (itm.querySelector('.banner__container__link'))
  4494. itm.style.display = 'none';
  4495. }
  4496. },
  4497.  
  4498. 'reactor.cc': {
  4499. other: 'joyreactor.cc, pornreactor.cc',
  4500. now: () => scriptLander(() => {
  4501. selectiveEval();
  4502. win.open = function () {
  4503. throw new ReferenceError('Redirect prevention.');
  4504. };
  4505. nt.define('Worker', nt.func(nt.proxy({}, 'Worker'), 'Worker'));
  4506. let _CTRManager = win.CTRManager;
  4507. Object.defineProperty(win, 'CTRManager', {
  4508. get() {
  4509. return _CTRManager;
  4510. },
  4511. set(vl) {
  4512. if (vl === _CTRManager)
  4513. return true;
  4514. _CTRManager = {};
  4515. for (let name in vl)
  4516. if (typeof vl[name] !== 'function')
  4517. _CTRManager[name] = vl[name];
  4518. _CTRManager = nt.proxy(_CTRManager, 'CTRManager');
  4519. }
  4520. });
  4521. }, nullTools, selectiveEval),
  4522. click(e) {
  4523. let node = e.target;
  4524. if (node.nodeType === _Node.ELEMENT_NODE &&
  4525. node.style.position === 'absolute' &&
  4526. node.style.zIndex > 0)
  4527. node.parentNode.removeChild(node);
  4528. }
  4529. },
  4530.  
  4531. 'rp5.tld': {
  4532. now() {
  4533. Object.defineProperty(win, 'sContentBottom', {
  4534. set() {},
  4535. get() {
  4536. return '';
  4537. }
  4538. });
  4539. // skip timeout check for blocked requests
  4540. let _setTimeout = win.setTimeout;
  4541. win.setTimeout = function setTimeout(...args) {
  4542. let str = (typeof args[0] === 'string' ? args[0] : _toString(args[0]));
  4543. if (str.includes('xvb')) {
  4544. _console.log('Blocked setTimeout for:', str);
  4545. return;
  4546. }
  4547. return _setTimeout(...args);
  4548. };
  4549. },
  4550. dom() {
  4551. let node = selectNodeByTextContent('Разместить текстовое объявление', {
  4552. root: _de.querySelector('#content-wrapper'),
  4553. shallow: true
  4554. });
  4555. if (node)
  4556. node.style.display = 'none';
  4557. }
  4558. },
  4559.  
  4560. 'rsload.net': {
  4561. load() {
  4562. let dis = _document.querySelector('label[class*="cb-disable"]');
  4563. if (dis)
  4564. dis.click();
  4565. },
  4566. click(e) {
  4567. let t = e.target;
  4568. if (t && t.href && (/:\/\/\d+\.\d+\.\d+\.\d+\//.test(t.href)))
  4569. t.href = t.href.replace('://', '://rsload.net:rsload.net@');
  4570. }
  4571. },
  4572.  
  4573. 'rustorka.tld': {
  4574. other: [
  4575. 'rustorka.innal.top, rustorka2.innal.top, rustorka3.innal.top',
  4576. 'rustorka4.innal.top, rustorka5.innal.top, rustorka6.innal.top',
  4577. 'rustorka.naylo.top'
  4578. ].join(', '),
  4579. now: () => scriptLander(() => {
  4580. selectiveCookies('~default|(?!(PHPSESSID|__cfduid|announcements|bb_data|bb_t|id|opt_js|shout)$).*');
  4581. selectiveEval(/antiadblock/);
  4582. abortExecution.onGet('ads_script');
  4583. abortExecution.inlineScript('setTimeout', {
  4584. pattern: /("(\\x[0-9A-F]{2})+",\s?){4}/
  4585. });
  4586.  
  4587. const _doc_proto = ('cookie' in _Document) ? _Document : Object.getPrototypeOf(_document);
  4588. const _cookie = Object.getOwnPropertyDescriptor(_doc_proto, 'cookie');
  4589.  
  4590. if (_cookie && GM.info.scriptHandler) {
  4591. const asyncCookieCleaner = () => {
  4592. GM.cookie.list({
  4593. url: location.href
  4594. }).then(cookies => {
  4595. for (let cookie of (cookies || []))
  4596. if (cookie.name === cookie.value) {
  4597. GM.cookie.delete(cookie);
  4598. _console.log(`Removed cookie: ${cookie.name}=${cookie.value}`);
  4599. }
  4600. });
  4601. };
  4602. _cookie.get = new Proxy(_cookie.get, {
  4603. apply(fun, that, args) {
  4604. asyncCookieCleaner();
  4605. return _apply(fun, that, args);
  4606. }
  4607. });
  4608. _cookie.set = new Proxy(_cookie.set, {
  4609. apply(fun, that, args) {
  4610. _apply(fun, that, args);
  4611. asyncCookieCleaner();
  4612. return true;
  4613. }
  4614. });
  4615. Object.defineProperty(_doc_proto, 'cookie', _cookie);
  4616. }
  4617. }, selectiveCookies, abortExecution),
  4618. dom: () => _document.cookie.slice(0, 0)
  4619. },
  4620.  
  4621. 'rutube.ru': () => scriptLander(() => {
  4622. jsonFilter('creative', 'creative.id');
  4623. jsonFilter('interactives', 'interactives.0');
  4624. }, jsonFilter),
  4625.  
  4626. 'sdamgia.ru': () => scriptLander(() => {
  4627. abortExecution.onGet('Object.prototype.getYa');
  4628. abortExecution.onGet('Object.prototype.initYa');
  4629. abortExecution.onGet('Object.prototype.initYaDirect');
  4630. }, abortExecution),
  4631.  
  4632. 'simpsonsua.com.ua': {
  4633. other: 'simpsonsua.tv',
  4634. now: () => scriptLander(() => {
  4635. let _addEventListener = _Document.addEventListener;
  4636. _document.addEventListener = function (event, callback) {
  4637. if (event === 'DOMContentLoaded' && callback.toString().includes('show_warning'))
  4638. return;
  4639. return _addEventListener.apply(this, arguments);
  4640. };
  4641. nt.define('need_warning', 0);
  4642. nt.define('onYouTubeIframeAPIReady', nt.func(null, 'onYouTubeIframeAPIReady'));
  4643. }, nullTools)
  4644. },
  4645.  
  4646. 'smotret-anime-365.ru': () => scriptLander(() => {
  4647. deepWrapAPI(root => {
  4648. const _pause = _bindCall(root.Audio.prototype.pause);
  4649. const _addEventListener = _bindCall(root.Element.prototype.addEventListener);
  4650. let stopper = e => _pause(e.target);
  4651. root.Audio = new Proxy(root.Audio, {
  4652. construct(audio, args) {
  4653. let res = _construct(audio, args);
  4654. _addEventListener(res, 'play', stopper, true);
  4655. return res;
  4656. }
  4657. });
  4658. let _tagName_get = _bindCall(Object.getOwnPropertyDescriptor(_Element, 'tagName').get);
  4659. root.Document.prototype.createElement = new Proxy(root.Document.prototype.createElement, {
  4660. apply(fun, that, args) {
  4661. let res = _apply(fun, that, args);
  4662. if (_tagName_get(res) === 'AUDIO')
  4663. _addEventListener(res, 'play', stopper, true);
  4664. return res;
  4665. }
  4666. });
  4667. });
  4668. }, deepWrapAPI),
  4669.  
  4670. 'spaces.ru': () => {
  4671. gardener('div:not(.f-c_fll) > a[href*="spaces.ru/?Cl="]', /./, {
  4672. parent: 'div'
  4673. });
  4674. gardener('.js-banner_rotator', /./, {
  4675. parent: '.widgets-group'
  4676. });
  4677. },
  4678.  
  4679. 'spam-club.blogspot.co.uk': () => {
  4680. let _clientHeight = Object.getOwnPropertyDescriptor(_Element, 'clientHeight'),
  4681. _clientWidth = Object.getOwnPropertyDescriptor(_Element, 'clientWidth');
  4682. let wrapGetter = (getter) => {
  4683. let _getter = getter;
  4684. return function () {
  4685. let _size = _getter.apply(this, arguments);
  4686. return _size ? _size : 1;
  4687. };
  4688. };
  4689. _clientHeight.get = wrapGetter(_clientHeight.get);
  4690. _clientWidth.get = wrapGetter(_clientWidth.get);
  4691. Object.defineProperty(_Element, 'clientHeight', _clientHeight);
  4692. Object.defineProperty(_Element, 'clientWidth', _clientWidth);
  4693. let _onload = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onload'),
  4694. _set_onload = _onload.set;
  4695. _onload.set = function () {
  4696. if (this instanceof HTMLImageElement)
  4697. return true;
  4698. _set_onload.apply(this, arguments);
  4699. };
  4700. Object.defineProperty(HTMLElement.prototype, 'onload', _onload);
  4701. },
  4702.  
  4703. 'sport-express.ru': () => gardener('.js-relap__item', />Реклама\s+<\//, {
  4704. root: '.container',
  4705. observe: true
  4706. }),
  4707.  
  4708. 'sports.ru': {
  4709. other: 'tribuna.com',
  4710. now() {
  4711. // extra functionality: shows/hides panel at the top depending on scroll direction
  4712. createStyle({
  4713. '.user-panel__fixed': {
  4714. transition: 'top 0.2s ease-in-out!important'
  4715. },
  4716. '.popup__overlay.feedback': {
  4717. display: 'none!important'
  4718. },
  4719. '.user-panel-up': {
  4720. top: '-40px!important'
  4721. },
  4722. '#branding-layout': {
  4723. margin_top: '100px!important'
  4724. }
  4725. }, {
  4726. id: 'fixes',
  4727. protect: false
  4728. });
  4729. scriptLander(() => {
  4730. yandexRavenStub();
  4731. webpackJsonpFilter(/AdBlockDetector|addBranding|loadPlista/);
  4732. }, nullTools, yandexRavenStub, webpackJsonpFilter);
  4733. },
  4734. dom() {
  4735. (function lookForPanel() {
  4736. let panel = _document.querySelector('.user-panel__fixed');
  4737. if (!panel)
  4738. setTimeout(lookForPanel, 100);
  4739. else
  4740. window.addEventListener(
  4741. 'wheel',
  4742. function (e) {
  4743. if (e.deltaY > 0 && !panel.classList.contains('user-panel-up'))
  4744. panel.classList.add('user-panel-up');
  4745. else if (e.deltaY < 0 && panel.classList.contains('user-panel-up'))
  4746. panel.classList.remove('user-panel-up');
  4747. }, false
  4748. );
  4749. })();
  4750. }
  4751. },
  4752.  
  4753. 'stealthz.ru': {
  4754. dom() {
  4755. // skip timeout
  4756. let $ = _document.querySelector.bind(_document);
  4757. let [timer_1, timer_2] = [$('#timer_1'), $('#timer_2')];
  4758. if (!timer_1 || !timer_2)
  4759. return;
  4760. timer_1.style.display = 'none';
  4761. timer_2.style.display = 'block';
  4762. }
  4763. },
  4764.  
  4765. 'tortuga.wtf': () => {
  4766. nt.define('Object.prototype.hideab', undefined);
  4767. },
  4768.  
  4769. 'tv.animebest.org': {
  4770. now() {
  4771. let _eval = win.eval;
  4772. win.eval = new win.Proxy(win.eval, {
  4773. apply(evl, ths, args) {
  4774. if (typeof args[0] === 'string' &&
  4775. args[0].includes("'VASTP'")) {
  4776. args[0] = args[0].replace("'VASTP'", "''");
  4777. win.eval = _eval;
  4778. }
  4779. return Reflect.apply(evl, ths, args);
  4780. }
  4781. });
  4782. }
  4783. },
  4784.  
  4785. 'tv-kanali.online': () => {
  4786. win.setTimeout = new Proxy(win.setTimeout, {
  4787. apply(fun, that, args) {
  4788. if (args[0].name && args[0].name.includes('doAd'))
  4789. return;
  4790. if (args[1] === 30000) args[1] = 100;
  4791. return _apply(fun, that, args);
  4792. }
  4793. });
  4794. },
  4795.  
  4796. 'video.khl.ru': () => {
  4797. let props = new Set(['detectBlockers', 'detectBlockersByLink', 'detectBlockersByElement']);
  4798. win.Object.defineProperty = new Proxy(win.Object.defineProperty, {
  4799. apply(def, that, args) {
  4800. if (props.has(args[1])) {
  4801. args[2] = {
  4802. key: args[1],
  4803. value() {
  4804. _console.log(`Skipped ${args[1]} call.`);
  4805. }
  4806. };
  4807. _console.log(`Replaced method ${args[1]}.`);
  4808. }
  4809. return Reflect.apply(def, that, args);
  4810. }
  4811. });
  4812. },
  4813.  
  4814. 'xatab-repack.net': {
  4815. other: 'rg-mechanics.org',
  4816. now() {
  4817. abortExecution.onSet('blocked');
  4818. }
  4819. },
  4820.  
  4821. 'xittv.net': () => scriptLander(() => {
  4822. let logNames = ['setup', 'trigger', 'on', 'off', 'onReady', 'onError', 'getConfig', 'addPlugin', 'getAdBlock'];
  4823. let skipEvents = ['adComplete', 'adSkipped', 'adBlock', 'adRequest', 'adMeta', 'adImpression', 'adError', 'adTime', 'adStarted', 'adClick'];
  4824. let _jwplayer;
  4825. Object.defineProperty(win, 'jwplayer', {
  4826. get() {
  4827. return _jwplayer;
  4828. },
  4829. set(x) {
  4830. _jwplayer = new Proxy(x, {
  4831. apply(fun, that, args) {
  4832. let res = fun.apply(that, args);
  4833. res = new Proxy(res, {
  4834. get(obj, name) {
  4835. if (logNames.includes(name) && typeof obj[name] === 'function')
  4836. return new Proxy(obj[name], {
  4837. apply(fun, that, args) {
  4838. if (name === 'setup') {
  4839. let o = args[0];
  4840. if (o)
  4841. delete o.advertising;
  4842. }
  4843. if (name === 'on' || name === 'trigger') {
  4844. let events = typeof args[0] === 'string' ? args[0].split(" ") : null;
  4845. if (events.length === 1 && skipEvents.includes(events[0]))
  4846. return res;
  4847. if (events.length > 1) {
  4848. let names = [];
  4849. for (let event of events)
  4850. if (!skipEvents.includes(event))
  4851. names.push(event);
  4852. if (names.length > 0)
  4853. args[0] = names.join(" ");
  4854. else
  4855. return res;
  4856. }
  4857. }
  4858. let subres = fun.apply(that, args);
  4859. _console.trace(`jwplayer().${name}(`, ...args, `) >>`, res);
  4860. return subres;
  4861. }
  4862. });
  4863. return obj[name];
  4864. }
  4865. });
  4866. return res;
  4867. }
  4868. });
  4869. _console.log('jwplayer =', x);
  4870. }
  4871. });
  4872. }),
  4873.  
  4874. 'yandex.tld': {
  4875. other: 'yandexsport.tld',
  4876. now: () => {
  4877. // Generic Yandex Scripts
  4878. const mainScript = () => {
  4879. let nt = new nullTools({
  4880. log: false,
  4881. trace: true
  4882. });
  4883.  
  4884. let cookiefilter = '';
  4885. // ads on afisha.yandex.ru, however it looks like selectiveEval isn't perfect
  4886. // since eval could be called in scope to access properties of that scope and
  4887. // such calls with it active break functionality on metrika.yandex.ru
  4888. if (/(^|\.)afisha\./.test(location.hostname)) {
  4889. selectiveEval(/AdvManagerStatic/);
  4890. nt.define('Object.prototype._adbStyles', null);
  4891. nt.define('Object.prototype._adbClass', null);
  4892. cookiefilter += (cookiefilter.length ? '|' : '') + 'checkcookie';
  4893. }
  4894.  
  4895. selectiveCookies(cookiefilter);
  4896. // remove banner on the start page
  4897. let AwapsJsonAPI_Json = function (...args) {
  4898. _console.log('>> new AwapsJsonAPI.Json(', ...args, ')');
  4899. };
  4900. const cleaner = (_params, nodes) => {
  4901. try {
  4902. for (let i = 0; i < nodes.length; i++)
  4903. nodes[i].parentNode.parentNode.removeChild(nodes[i].parentNode);
  4904. _console.log(`Removed banner placeholder.`);
  4905. } catch (ignore) {
  4906. _console.log(`Can't locate placeholder to remove.`);
  4907. }
  4908. };
  4909. Object.assign(AwapsJsonAPI_Json.prototype, {
  4910. checkBannerVisibility: nt.func(true, 'AwapsJsonAPI.Json.checkBannerVisibility'),
  4911. autorefresh: nt.proxy(cleaner, 'AwapsJsonAPI.Json.prototype.autorefresh'),
  4912. addIframeContent: nt.proxy(cleaner, 'AwapsJsonAPI.Json.prototype.addIframeContent'),
  4913. getHTML: nt.func('', 'AwapsJsonAPI.Json.getHTML')
  4914. });
  4915. AwapsJsonAPI_Json.prototype = nt.proxy(AwapsJsonAPI_Json.prototype, 'AwapsJsonAPI.Json.prototype');
  4916. AwapsJsonAPI_Json = nt.proxy(AwapsJsonAPI_Json);
  4917. if ('AwapsJsonAPI' in win) {
  4918. _console.log('Oops! AwapsJsonAPI already defined.');
  4919. let f = win.AwapsJsonAPI.Json;
  4920. win.AwapsJsonAPI.Json = AwapsJsonAPI_Json;
  4921. if (f && f.prototype)
  4922. f.prototype = AwapsJsonAPI_Json.prototype;
  4923. } else
  4924. nt.define('AwapsJsonAPI', nt.proxy({
  4925. Json: AwapsJsonAPI_Json
  4926. }));
  4927.  
  4928. let parseExport = x => {
  4929. if (!x)
  4930. return x;
  4931. // remove banner placeholder
  4932. if (x.banner && x.banner.cls && x.banner.cls.banner__parent) {
  4933. let hide = pattern => {
  4934. for (let banner of _document.querySelectorAll(pattern)) {
  4935. _setAttribute(banner, 'style', 'display:none!important');
  4936. _console.log('Hid banner placeholder.');
  4937. }
  4938. };
  4939. let _parent = `.${x.banner.cls.banner__parent}`;
  4940. hide(_parent);
  4941. _document.addEventListener('DOMContentLoaded', () => hide(_parent), false);
  4942. }
  4943.  
  4944. // remove banner data and some other stuff
  4945. delete x.banner;
  4946. delete x.consistency;
  4947. delete x['i-bannerid'];
  4948. delete x['i-counter'];
  4949. delete x['promo-curtain'];
  4950.  
  4951. // remove parts of ga-counter (complete removal break "ТВ Онлайн")
  4952. if (x['ga-counter'] && x['ga-counter'].data) {
  4953. x['ga-counter'].data.id = 0;
  4954. delete x['ga-counter'].data.ether;
  4955. delete x['ga-counter'].data.iframeSrc;
  4956. delete x['ga-counter'].data.iframeSrcEx;
  4957. }
  4958.  
  4959. // remove adblock detector parameters and clean up detector cookie
  4960. if ('adb' in x) {
  4961. let cookie = x.adb.data ? x.adb.data.cookie : undefined;
  4962. if (cookie) {
  4963. selectiveCookies(cookie);
  4964. x.adb.data.adb = 0;
  4965. }
  4966. delete x.adb;
  4967. }
  4968.  
  4969. return x;
  4970. };
  4971. // Yandex banner on main page and some other things
  4972. let _home = win.home,
  4973. _home_set = !!_home;
  4974. Object.defineProperty(win, 'home', {
  4975. get() {
  4976. return _home;
  4977. },
  4978. set(vl) {
  4979. if (!_home_set && vl === _home)
  4980. return;
  4981. _home_set = false;
  4982. _console.log('home =', vl);
  4983. let _home_export = parseExport(vl.export);
  4984. Object.defineProperty(vl, 'export', {
  4985. get() {
  4986. return _home_export;
  4987. },
  4988. set(vl) {
  4989. _home_export = parseExport(vl);
  4990. }
  4991. });
  4992. _home = vl;
  4993. }
  4994. });
  4995.  
  4996. // adblock circumvention on some Yandex domains
  4997. yandexRavenStub();
  4998.  
  4999. // news, sport, docviewer in emails and probably other places
  5000. abortExecution.onGet('yaads.adRenderedCount');
  5001. let AdvertPartner = nt.func(false, 'AdvertPartner');
  5002. nt.defineOn(AdvertPartner, 'defaultProps', {}, 'AdvertPartner.');
  5003. nt.defineOn(AdvertPartner, 'contextTypes', [], 'AdvertPartner.');
  5004. nt.define('Object.prototype.AdvertPartner', AdvertPartner);
  5005. // ads in videoplayer
  5006. nt.define('Object.prototype.useAbdBundle', false);
  5007.  
  5008. // code specific for /news and /sport
  5009. if (/^\/news(\/|$)/.test(location.pathname)) {
  5010. createStyle(
  5011. 'div[class]:not(.mg-grid__col) > .mg-grid__row > .mg-grid__col:last-child,' +
  5012. '.news-top-rubric-heading > span:only-child { display: none !important }'
  5013. );
  5014. gardener('.mg-grid__col > div[class*="_type_"]', /./, {
  5015. root: '.news-app__feed',
  5016. parent: '.mg-grid__col',
  5017. observe: true,
  5018. hide: true
  5019. });
  5020. }
  5021. if (/^\/sport(\/|$)/.test(location.pathname))
  5022. createStyle('.sport-advert_type_card { display: none !important }');
  5023.  
  5024. // abp detector cookie on yandex pogoda and afisha
  5025. win.Element.prototype.getAttribute = new Proxy(win.Element.prototype.getAttribute, {
  5026. apply(get, el, args) {
  5027. let res = _apply(get, el, args);
  5028. if (res && res.length > 20 && el instanceof HTMLBodyElement)
  5029. try {
  5030. let o = JSON.parse(res),
  5031. found = false,
  5032. check;
  5033. for (let prop in o) {
  5034. check = 'param' in o[prop] || 'aabCookieName' in o[prop];
  5035. if (check || 'banners' in o[prop]) {
  5036. found = true;
  5037. if (check)
  5038. selectiveCookies(o[prop].param || o[prop].aabCookieName);
  5039. _console.log(el.tagName, o, 'removed', o[prop]);
  5040. delete o[prop];
  5041. }
  5042. }
  5043. if (!found) _console.log(el.tagName, o);
  5044. res = JSON.stringify(o);
  5045. } catch (ignore) {}
  5046. return res;
  5047. }
  5048. });
  5049. };
  5050. scriptLander(mainScript, nullTools, yandexRavenStub, abortExecution, selectiveCookies, selectiveEval);
  5051.  
  5052. if ('attachShadow' in _Element) try {
  5053. let fakeRoot = () => ({
  5054. firstChild: null,
  5055. appendChild() {
  5056. return null;
  5057. },
  5058. querySelector() {
  5059. return null;
  5060. },
  5061. querySelectorAll() {
  5062. return null;
  5063. }
  5064. });
  5065. _Element.createShadowRoot = fakeRoot;
  5066. let shadows = new WeakMap();
  5067. let _attachShadow = Object.getOwnPropertyDescriptor(_Element, 'attachShadow');
  5068. _attachShadow.value = function () {
  5069. return shadows.set(this, fakeRoot()).get(this);
  5070. };
  5071. Object.defineProperty(_Element, 'attachShadow', _attachShadow);
  5072. let _shadowRoot = Object.getOwnPropertyDescriptor(_Element, 'shadowRoot');
  5073. _shadowRoot.set = () => null;
  5074. _shadowRoot.get = function () {
  5075. return shadows.has(this) ? shadows.get(this) : undefined;
  5076. };
  5077. Object.defineProperty(_Element, 'shadowRoot', _shadowRoot);
  5078. } catch (e) {
  5079. _console.warn('Unable to wrap Element.prototype.attachShadow\n', e);
  5080. }
  5081.  
  5082. // Disable banner styleSheet (on main page)
  5083. document.addEventListener('DOMContentLoaded', () => {
  5084. for (let sheet of document.styleSheets)
  5085. try {
  5086. for (let rule of sheet.cssRules)
  5087. if (rule.cssText.includes(' 728px 90px')) {
  5088. rule.parentStyleSheet.disabled = true;
  5089. _console.log('Disabled banner styleSheet:', rule.parentStyleSheet);
  5090. }
  5091. } catch (ignore) {}
  5092. }, false);
  5093.  
  5094. // Subdomain-specific Yandex scripts
  5095. const subDomain = location.hostname.slice(0, location.hostname.indexOf('.'));
  5096.  
  5097. // Yandex Mail ads
  5098. if (subDomain === 'mail') {
  5099. let wrap = vl => {
  5100. if (!vl)
  5101. return vl;
  5102. _console.log('Daria =', vl);
  5103. nt.defineOn(vl, 'AdBlock', nt.proxy({
  5104. detect: nt.func(new Promise(() => null), 'Daria.AdBlock.detect'),
  5105. enabled: false
  5106. }), 'Daria.');
  5107. nt.defineOn(vl, 'AdvPresenter', nt.proxy({
  5108. _config: nt.proxy({
  5109. banner: false,
  5110. done: false,
  5111. line: false
  5112. })
  5113. }), 'Daria.');
  5114. if (vl.Config) {
  5115. delete vl.Config.adBlockDetector;
  5116. delete vl.Config['adv-url'];
  5117. delete vl.Config.cryprox;
  5118. if (vl.Config.features) {
  5119. delete vl.Config.features.web_adloader_with_cookie_cache;
  5120. delete vl.Config.features.web_ads;
  5121. delete vl.Config.features.web_ads_mute;
  5122. }
  5123. vl.Config.mayHaveAdv = false;
  5124. }
  5125. return vl;
  5126. };
  5127. let _Daria = wrap(win.Daria);
  5128. if (_Daria)
  5129. _console.log('Wrapped already existing object "Daria".');
  5130. Object.defineProperty(win, 'Daria', {
  5131. get() {
  5132. return _Daria;
  5133. },
  5134. set(vl) {
  5135. if (vl === _Daria)
  5136. return;
  5137. _Daria = wrap(vl);
  5138. }
  5139. });
  5140. }
  5141.  
  5142. // Detector and ads on Yandex Music
  5143. if (subDomain === 'music') {
  5144. nt.define('tryPay', nt.func(null, 'tryPay'));
  5145. nt.define('Object.prototype.initMegabannerAPI', nt.func(null, 'initMegabannerAPI'));
  5146. nt.define('Object.prototype.mediaAd', undefined);
  5147. nt.define('Object.prototype.detect', () => new Promise(() => null));
  5148. nt.define('Object.prototype.loadContext', () => new Promise(r => r()));
  5149. nt.define('Object.prototype.antiAdbSetup', nt.func(null, 'ya.music.antiAdbSetup'));
  5150. }
  5151.  
  5152. const isSearch = /^\/(yand)?search[/?]/i.test(location.pathname);
  5153. if (['mail', 'music', 'tv', 'yandexsport'].includes(subDomain) || isSearch) {
  5154. // prevent/defuse adblock detector and cleanup localStorage
  5155. for (let name in localStorage)
  5156. if (name.startsWith('videoplayer-ad-session-') || ['ic', 'yu', 'ludca', 'test'].includes(name))
  5157. localStorage.removeItem(name);
  5158. nt.define('localStorage._mt__data', '');
  5159. nt.define('localStorage.yandexJSPlayerApiSavedSingleVideoSessionWatchedTimeSinceAd', Math.random() * 1000);
  5160.  
  5161. // cookie cleaner
  5162. let yp_keepCookieParts = /\.(sp|ygo|ygu)\./; // ygo = city id; ygu = detect city automatically
  5163. let _doc_proto = ('cookie' in _Document) ? _Document : Object.getPrototypeOf(_document);
  5164. let _cookie = Object.getOwnPropertyDescriptor(_doc_proto, 'cookie');
  5165. if (_cookie) {
  5166. let _set_cookie = _bindCall(_cookie.set);
  5167. _cookie.set = function (value) {
  5168. if (/^(mda=|yp=|ys=|yabs-|__|bltsr=)/.test(value))
  5169. // remove value, set expired
  5170. if (!value.startsWith('yp=')) {
  5171. value = value.replace(/^([^=]+=)[^;]+/, '$1').replace(/(expires=)[\w\s\d,]+/, '$1Thu, 01 Jan 1970 00');
  5172. _console.trace('expire cookie', value.match(/^[^=]+/)[0]);
  5173. } else {
  5174. let parts = value.split(';');
  5175. let values = parts[0].split('#').filter(part => yp_keepCookieParts.test(part));
  5176. if (values.length)
  5177. values[0] = values[0].replace(/^yp=/, '');
  5178. let res = `yp=${values.join('#')}`;
  5179. _console.trace(`set cookie ${res}, dropped ${parts[0].replace(res,'')}`);
  5180. parts[0] = res;
  5181. value = parts.join(';');
  5182. }
  5183. return _set_cookie(this, value);
  5184. };
  5185. Object.defineProperty(_doc_proto, 'cookie', _cookie);
  5186. }
  5187. }
  5188. },
  5189. dom: () => {
  5190. { // Partially based on https://greasyfork.org/en/scripts/22737-remove-yandex-redirect
  5191. let count = 0,
  5192. lock = false;
  5193. const log = () => {
  5194. count++;
  5195. if (lock)
  5196. return;
  5197. setTimeout(() => {
  5198. _console.log('Removed tracking attributes from', count, 'links.');
  5199. count = 0;
  5200. lock = false;
  5201. }, 3333);
  5202. lock = true;
  5203. };
  5204. const selectors = (
  5205. 'A[onmousedown*="/jsredir"],' +
  5206. 'A[data-log-node],' +
  5207. 'A[data-vdir-href],' +
  5208. 'A[data-counter]'
  5209. );
  5210. const removeTrackingAttributes = (link) => {
  5211. _removeAttribute(link, 'onmousedown');
  5212. _removeAttribute(link, 'data-log-node');
  5213. // data-vdir-href
  5214. _removeAttribute(link, 'data-vdir-href');
  5215. _removeAttribute(link, 'data-orig-href');
  5216. // data-counter
  5217. _removeAttribute(link, 'data-counter');
  5218. _removeAttribute(link, 'data-bem');
  5219. log();
  5220. };
  5221. const removeTracking = (scope) => {
  5222. if (scope instanceof Element)
  5223. for (let link of scope.querySelectorAll(selectors))
  5224. removeTrackingAttributes(link);
  5225. };
  5226.  
  5227. removeTracking(_document);
  5228. (new MutationObserver(
  5229. function (ms) {
  5230. let m, node;
  5231. for (m of ms)
  5232. for (node of m.addedNodes)
  5233. if (node instanceof HTMLAnchorElement && node.matches(selectors))
  5234. removeTrackingAttributes(node);
  5235. else
  5236. removeTracking(node);
  5237. }
  5238. )).observe(_de, {
  5239. childList: true,
  5240. subtree: true
  5241. });
  5242. }
  5243.  
  5244. // Subdomain-specific Yandex scripts
  5245. const subDomain = location.hostname.slice(0, location.hostname.indexOf('.'));
  5246.  
  5247. // Function to attach an observer to monitor dynamic changes on the page
  5248. const pageUpdateObserver = (func, obj, params) => {
  5249. if (obj)
  5250. (new MutationObserver(func))
  5251. .observe(obj, (params || {
  5252. childList: true,
  5253. subtree: true
  5254. }));
  5255. };
  5256. // Short name for parentNode.removeChild
  5257. const remove = node => {
  5258. if (!node || !node.parentNode)
  5259. return false;
  5260. _console.log('Removed node.');
  5261. node.parentNode.removeChild(node);
  5262. };
  5263. // Short name for setAttribute style to display:none
  5264. const hide = node => {
  5265. if (!node)
  5266. return false;
  5267. _console.log('Hid node.');
  5268. _setAttribute(node, 'style', 'display:none!important');
  5269. };
  5270.  
  5271. if (subDomain === 'music') {
  5272. const removeMusicAds = () => {
  5273. for (let node of _querySelectorAll('.ads-block'))
  5274. remove(node);
  5275. };
  5276. pageUpdateObserver(removeMusicAds, _querySelector('.sidebar'));
  5277. removeMusicAds();
  5278. }
  5279.  
  5280. if (subDomain === 'tv') {
  5281. const removeTVAds = () => {
  5282. const yadWord = /Яндекс.Директ/i;
  5283. for (let node of _querySelectorAll('div[class^="_"][data-reactid] > div'))
  5284. if (yadWord.test(node.textContent) || node.querySelector('iframe:not([src])')) {
  5285. if (node.offsetWidth) {
  5286. let pad = _document.createElement('div');
  5287. _setAttribute(pad, 'style', `width:${node.offsetWidth}px`);
  5288. node.parentNode.appendChild(pad);
  5289. }
  5290. remove(node);
  5291. }
  5292. };
  5293. pageUpdateObserver(removeTVAds, _document.body);
  5294. removeTVAds();
  5295. }
  5296.  
  5297. const isSearch = /^\/(yand)?search[/?]/i.test(location.pathname);
  5298. if (isSearch) {
  5299. const removeSearchAds = () => {
  5300. const adWords = /Реклама|Ad/i;
  5301. for (let node of _querySelectorAll('.serp-item'))
  5302. if (_getAttribute(node, 'role') === 'complementary' ||
  5303. adWords.test((node.querySelector('.label') || {}).textContent))
  5304. hide(node);
  5305. };
  5306. pageUpdateObserver(removeSearchAds, _querySelector('.main__content'));
  5307. removeSearchAds();
  5308. }
  5309.  
  5310. if (['mail', 'music', 'tv', 'yandexsport'].includes(subDomain) || isSearch) {
  5311. // Generic ads removal and fixes
  5312. for (let node of _querySelectorAll('.serp-header'))
  5313. node.style.marginTop = '0';
  5314. for (let node of _querySelectorAll(
  5315. '.serp-adv__head + .serp-item,' +
  5316. '#adbanner,' +
  5317. '.serp-adv,' +
  5318. '.b-spec-adv,' +
  5319. 'div[class*="serp-adv__"]:not(.serp-adv__found):not(.serp-adv__displayed)'
  5320. )) remove(node);
  5321. }
  5322. }
  5323. },
  5324.  
  5325. 'yap.ru': {
  5326. other: 'yaplakal.com',
  5327. now() {
  5328. gardener('form > table[id^="p_row_"]:nth-of-type(2)', /member1438|Administration/);
  5329. gardener('.icon-comments', /member1438|Administration|\/go\/\?http/, {
  5330. parent: 'tr',
  5331. siblings: -2
  5332. });
  5333. }
  5334. },
  5335.  
  5336. 'yapx.ru': () => scriptLander(() => {
  5337. selectiveCookies('adblock_state|adblock_views');
  5338. nt.define('blockAdBlock', {
  5339. on: nt.func(nt.proxy({}, 'blockAdBlock.on', nt.NULL), 'blockAdBlock.on'),
  5340. check: nt.func(null, 'blockAdBlock.check')
  5341. });
  5342. }, selectiveCookies, nullTools),
  5343.  
  5344. 'youtube.com': () => scriptLander(() => {
  5345. jsonFilter('playerResponse.adPlacements playerResponse.playerAds adPlacements playerAds');
  5346. }, jsonFilter),
  5347.  
  5348. 'znanija.com': () => scriptLander(() => {
  5349. localStorage.clear();
  5350. }, abortExecution)
  5351. };
  5352.  
  5353. // replace '.tld' in domain names, add alternative domain names if present and wrap functions into objects
  5354. {
  5355. const parts = _document.domain.split('.');
  5356. const tld = /\.tld$/;
  5357. const tldSubstitur = (() => {
  5358. // stores TLD of current domain (simplistic TLD implementation)
  5359. const last = parts.length - 1;
  5360. const tld = ['', parts[last]];
  5361. const secondLevel = [
  5362. 'biz', 'com', 'edu', 'gov', 'info', 'int', 'mil', 'net', 'org', 'pro'
  5363. ];
  5364. // add second from the end part of domain name as part of the TLD substitutor
  5365. // when domain name consists of more than 2 parts and it looks like a part of TLD
  5366. if ((parts[0] !== 'www' && parts.length > 2 || parts.length > 3) &&
  5367. (parts[last - 1].length < 3 || secondLevel.includes(parts[last - 1])))
  5368. tld.splice(0, 1, parts[last - 1]);
  5369. return tld.join('.');
  5370. })();
  5371. for (let name in scripts) {
  5372. if (typeof scripts[name] === 'function')
  5373. scripts[name] = {
  5374. now: scripts[name]
  5375. };
  5376. if (name.endsWith('.tld'))
  5377. scripts[name.replace(tld, tldSubstitur)] = scripts[name];
  5378. for (let domain of (scripts[name].other && scripts[name].other.split(/,\s*/) || [])) {
  5379. domain = domain.replace(tld, tldSubstitur);
  5380. if (domain in scripts)
  5381. _console.log('Error in scripts list. Script for', name, 'replaced script for', domain);
  5382. scripts[domain] = scripts[name];
  5383. }
  5384. delete scripts[name].other;
  5385. }
  5386. // scripts lookup
  5387. const windowEvents = ['load', 'unload', 'beforeunload'];
  5388. let domain;
  5389. while (parts.length > 1) {
  5390. domain = parts.join('.');
  5391. if (domain in scripts) {
  5392. for (let when in scripts[domain]) {
  5393. let script = scripts[domain][when];
  5394. if (when === 'now')
  5395. script();
  5396. else if (when === 'dom')
  5397. _document.addEventListener('DOMContentLoaded', script);
  5398. else if (windowEvents.includes(when))
  5399. win.addEventListener(when, scripts[domain][when]);
  5400. else
  5401. _document.addEventListener(when, scripts[domain][when]);
  5402. }
  5403. }
  5404. parts.shift();
  5405. }
  5406. }
  5407.  
  5408. // Batch script lander
  5409. if (!skipLander)
  5410. landScript(batchLand, batchPrepend);
  5411.  
  5412. { // JS Fixes Tools Menu
  5413. const incompatibleScriptHandler = !/^(Tamper|Violent)monkey$/.test(GM.info.scriptHandler) || GM.info.scriptHandler === 'Violentmonkey' && isFirefox;
  5414. // Debug function, lists all unusual window properties
  5415. const isNativeFunction = /^[^{]*\{[\s\r\n]*\[native\scode\][\s\r\n]*\}$/;
  5416. const getStrangeObjectsList = () => {
  5417. _console.group('Window strangers list');
  5418. const _skip = 'frames/self/window/webkitStorageInfo'.split('/');
  5419. for (let n of Object.getOwnPropertyNames(win))
  5420. try {
  5421. let val = win[n];
  5422. if (val && !_skip.includes(n) && (win !== window && val !== window[n] || win === window) &&
  5423. (typeof val !== 'function' || typeof val === 'function' && !isNativeFunction.test(_toString(val))))
  5424. _console.log(`${n} =`, val);
  5425. } catch (e) {
  5426. _console.log(n, 'returns error on read', e);
  5427. }
  5428. _console.groupEnd('Window strangers list');
  5429. };
  5430.  
  5431. const lines = {
  5432. linked: [],
  5433. MenuOptions: {
  5434. eng: 'Options',
  5435. rus: 'Настройки'
  5436. },
  5437. MenuCompatibilityWarning: {
  5438. eng: 'is not supported',
  5439. rus: 'не поддерживается'
  5440. },
  5441. langs: {
  5442. eng: 'English',
  5443. rus: 'Русский'
  5444. },
  5445. sObjBtn: {
  5446. eng: 'List unusual "window" properties in console',
  5447. rus: 'Вывести в консоль нестандартные свойства «window»'
  5448. },
  5449. HeaderTools: {
  5450. eng: 'Tools',
  5451. rus: 'Инструменты'
  5452. },
  5453. HeaderOptions: {
  5454. eng: 'Options',
  5455. rus: 'Настройки'
  5456. },
  5457. AccessStatisticsLabel: {
  5458. eng: 'Display stubs access statistics and JSON filter',
  5459. rus: 'Выводить статистику запросов к заглушкам и JSON фильтра'
  5460. },
  5461. AbortExecutionStatisticsLabel: {
  5462. eng: 'Display abort execution statistics',
  5463. rus: 'Выводить статистику прерывания исполнения скриптов'
  5464. },
  5465. LogAttachedCSSLabel: {
  5466. eng: 'Log CSS attached to a page',
  5467. rus: 'Журналировать CSS добавленные на страницу'
  5468. },
  5469. BlockNotificationPermissionRequestsLabel: {
  5470. eng: 'Block requests to Show Notifications on sites',
  5471. rus: 'Блокировать запросы Показывать Уведомления на сайтах'
  5472. },
  5473. ShowScriptHandlerCompatibilityWarningLabel: {
  5474. eng: 'Show compatibility warning in menu next to Options',
  5475. rus: 'Отображать предупреждение о совместимости в меню рядом с Настройками'
  5476. },
  5477. reg(el, name) {
  5478. this[name].link = el;
  5479. this.linked.push(name);
  5480. },
  5481. setLang(lang = 'eng') {
  5482. for (let name of this.linked) {
  5483. const el = this[name].link;
  5484. const label = this[name][lang];
  5485. el.textContent = label;
  5486. }
  5487. this.langs.link.value = lang;
  5488. jsf.Lang = lang;
  5489. }
  5490. };
  5491.  
  5492. const _createTextNode = _Document.createTextNode.bind(_document);
  5493. const createOptionsWindow = () => {
  5494. const root = _createElement('div'),
  5495. shadow = _attachShadow ? _attachShadow(root, {
  5496. mode: 'closed'
  5497. }) : root,
  5498. overlay = _createElement('div'),
  5499. inner = _createElement('div');
  5500.  
  5501. overlay.id = 'overlay';
  5502. overlay.appendChild(inner);
  5503. shadow.appendChild(overlay);
  5504.  
  5505. inner.id = 'inner';
  5506. inner.br = function appendBreakLine() {
  5507. return this.appendChild(_createElement('br'));
  5508. };
  5509.  
  5510. createStyle({
  5511. 'h2': {
  5512. margin_top: 0
  5513. },
  5514. 'h2, h3': {
  5515. margin_block_end: '0.5em'
  5516. },
  5517. 'div, button, select, input': {
  5518. font_family: 'Helvetica, Arial, sans-serif',
  5519. font_size: '12pt'
  5520. },
  5521. 'button': {
  5522. background: 'linear-gradient(to bottom, #f0f0f0 5%, #c0c0c0 100%)',
  5523. border_radius: '3px',
  5524. border: '1px solid #a1a1a1',
  5525. color: '#000000',
  5526. text_shadow: '0px 1px 0px #d4d4d4'
  5527. },
  5528. 'button:hover': {
  5529. background: 'linear-gradient(to bottom, #c0c0c0 5%, #f0f0f0 100%)'
  5530. },
  5531. 'button:active': {
  5532. position: 'relative',
  5533. top: '1px'
  5534. },
  5535. 'select': {
  5536. border: '1px solid darkgrey',
  5537. border_radius: '0px 0px 5px 5px',
  5538. border_top: '0px'
  5539. },
  5540. 'button:focus, select:focus': {
  5541. outline: 'none'
  5542. },
  5543. '#overlay': {
  5544. position: 'fixed',
  5545. top: 0,
  5546. left: 0,
  5547. bottom: 0,
  5548. right: 0,
  5549. background: 'rgba(0,0,0,0.65)',
  5550. z_index: 2147483647 // Highest z-index: Math.pow(2, 31) - 1
  5551. },
  5552. '#inner': {
  5553. background: 'whitesmoke',
  5554. color: 'black',
  5555. padding: '1.5em 1em 1.5em 1em',
  5556. max_width: '150ch',
  5557. position: 'absolute',
  5558. top: '50%',
  5559. left: '50%',
  5560. transform: 'translate(-50%, -50%)',
  5561. border: '1px solid darkgrey',
  5562. border_radius: '5px'
  5563. },
  5564. '#closeOptionsButton': {
  5565. float: 'right',
  5566. transform: 'translate(1em, -1.5em)',
  5567. border: 0,
  5568. border_radius: 0,
  5569. background: 'none',
  5570. box_shadow: 'none'
  5571. },
  5572. '#selectLang': {
  5573. float: 'right',
  5574. transform: 'translate(0, -1.5em)'
  5575. },
  5576. '.optionsLabel': {
  5577. padding_left: '1.5em',
  5578. text_indent: '-1em',
  5579. display: 'block'
  5580. },
  5581. '.optionsCheckbox': {
  5582. left: '-0.25em',
  5583. width: '1em',
  5584. height: '1em',
  5585. padding: 0,
  5586. margin: 0,
  5587. position: 'relative',
  5588. vertical_align: 'middle'
  5589. },
  5590. '@media (prefers-color-scheme: dark)': {
  5591. '#inner': {
  5592. background_color: '#292a2d',
  5593. color: 'white',
  5594. border: '1px solid #1a1b1e'
  5595. },
  5596. 'input': {
  5597. filter: 'invert(100%)'
  5598. },
  5599. 'button': {
  5600. background: 'linear-gradient(to bottom, #575757 5%, #303030 100%)',
  5601. border_color: '#575757',
  5602. color: '#f0f0f0',
  5603. text_shadow: '0px 1px 0px #171717'
  5604. },
  5605. 'button:hover': {
  5606. background: 'linear-gradient(to bottom, #303030 5%, #575757 100%)'
  5607. },
  5608. 'select': {
  5609. background_color: '#303030',
  5610. color: '#f0f0f0',
  5611. border: '1px solid #1a1b1e',
  5612. border_radius: '0px 0px 5px 5px',
  5613. border_top: '0px'
  5614. },
  5615. '#overlay': {
  5616. background: 'rgba(0,0,0,.85)',
  5617. }
  5618. }
  5619. }, {
  5620. root: shadow,
  5621. protect: false
  5622. });
  5623.  
  5624. // components
  5625. function createCheckbox(name) {
  5626. const checkbox = _createElement('input'),
  5627. label = _createElement('label');
  5628. checkbox.type = 'checkbox';
  5629. checkbox.classList.add('optionsCheckbox');
  5630. checkbox.checked = jsf[name];
  5631. checkbox.onclick = e => {
  5632. jsf[name] = e.target.checked;
  5633. return true;
  5634. };
  5635. label.classList.add('optionsLabel');
  5636. label.appendChild(checkbox);
  5637. const text = _createTextNode('');
  5638. label.appendChild(text);
  5639. Object.defineProperty(label, 'textContent', {
  5640. set(title) {
  5641. text.textContent = title;
  5642. }
  5643. });
  5644. return label;
  5645. }
  5646.  
  5647. // language & close
  5648. const closeBtn = _createElement('button');
  5649. closeBtn.onclick = () => _removeChild(root);
  5650. closeBtn.textContent = '\u2715';
  5651. closeBtn.id = 'closeOptionsButton';
  5652. inner.appendChild(closeBtn);
  5653.  
  5654. overlay.addEventListener('click', e => {
  5655. if (e.target === overlay) {
  5656. _removeChild(root);
  5657. e.preventDefault();
  5658. }
  5659. e.stopPropagation();
  5660. }, false);
  5661.  
  5662. const selectLang = _createElement('select');
  5663. for (let name in lines.langs) {
  5664. const langOption = _createElement('option');
  5665. langOption.value = name;
  5666. langOption.innerText = lines.langs[name];
  5667. selectLang.appendChild(langOption);
  5668. }
  5669. selectLang.id = 'selectLang';
  5670. lines.langs.link = selectLang;
  5671. inner.appendChild(selectLang);
  5672.  
  5673. selectLang.onchange = e => {
  5674. const lang = e.target.value;
  5675. lines.setLang(lang);
  5676. };
  5677.  
  5678. // fill options form
  5679. const header = _createElement('h2');
  5680. header.textContent = 'RU AdList JS Fixes';
  5681. inner.appendChild(header);
  5682.  
  5683. lines.reg(inner.appendChild(_createElement('h3')), 'HeaderTools');
  5684.  
  5685. const sObjBtn = _createElement('button');
  5686. sObjBtn.onclick = getStrangeObjectsList;
  5687. sObjBtn.textContent = '';
  5688. lines.reg(inner.appendChild(sObjBtn), 'sObjBtn');
  5689.  
  5690. lines.reg(inner.appendChild(_createElement('h3')), 'HeaderOptions');
  5691.  
  5692. lines.reg(inner.appendChild(createCheckbox('AccessStatistics')), 'AccessStatisticsLabel');
  5693. lines.reg(inner.appendChild(createCheckbox('AbortExecutionStatistics')), 'AbortExecutionStatisticsLabel');
  5694. lines.reg(inner.appendChild(createCheckbox('LogAttachedCSS')), 'LogAttachedCSSLabel');
  5695.  
  5696. inner.appendChild(_createElement('br'));
  5697. lines.reg(inner.appendChild(createCheckbox('BlockNotificationPermissionRequests')), 'BlockNotificationPermissionRequestsLabel');
  5698.  
  5699. if (incompatibleScriptHandler) {
  5700. inner.appendChild(_createElement('br'));
  5701. lines.reg(inner.appendChild(createCheckbox('ShowScriptHandlerCompatibilityWarning')), 'ShowScriptHandlerCompatibilityWarningLabel');
  5702. }
  5703.  
  5704. lines.setLang(jsf.Lang);
  5705.  
  5706. return root;
  5707. };
  5708.  
  5709. let optionsWindow;
  5710. GM_registerMenuCommand(lines.MenuOptions[jsf.Lang], () => _appendChild(optionsWindow = optionsWindow || createOptionsWindow()));
  5711. // add warning to script menu for non-Tampermonkey users
  5712. if (jsf.ShowScriptHandlerCompatibilityWarning && incompatibleScriptHandler)
  5713. GM_registerMenuCommand(`${GM.info.scriptHandler} ${lines.MenuCompatibilityWarning[jsf.Lang]}`, () => {
  5714. win.open(`https://greasyfork.org/${opts.Lang.slice(0,2)}/scripts/19993-ru-adlist-js-fixes#additional-info`);
  5715. });
  5716. }
  5717. })();