RU AdList JS Fixes

try to take over the world!

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

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