RU AdList JS Fixes

try to take over the world!

目前为 2021-03-05 提交的版本。查看 最新版本

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