RU AdList JS Fixes

try to take over the world!

当前为 2021-01-04 提交的版本,查看 最新版本

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