RU AdList JS Fixes

try to take over the world!

当前为 2021-02-23 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name RU AdList JS Fixes
  3. // @namespace ruadlist_js_fixes
  4. // @version 20210223.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. display: 'block !important'
  3202. }
  3203. });
  3204. let _contentWindow = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, 'contentWindow');
  3205. let _get_contentWindow = _bindCall(_contentWindow.get);
  3206. _contentWindow.get = function () {
  3207. let res = _get_contentWindow(this);
  3208. if (res.location.href === 'about:blank')
  3209. res.document.write = (...args) => _console.log('Skipped iframe.write(', ...args, ')');
  3210. return res;
  3211. };
  3212. Object.defineProperty(HTMLIFrameElement.prototype, 'contentWindow', _contentWindow);
  3213. }),
  3214. dom() {
  3215. let list = _querySelectorAll('div[id^="yandex_rtb_"], .adsbygoogle');
  3216. list.forEach(node => _console.log('Removed:', node.parentNode.parentNode.removeChild(node.parentNode)));
  3217. }
  3218. },
  3219.  
  3220. 'drive2.ru': () => {
  3221. gardener('.c-block:not([data-metrika="recomm"]),.o-grid__item', />Реклама<\//i);
  3222. scriptLander(() => {
  3223. selectiveCookies();
  3224. let _d2;
  3225. Object.defineProperty(win, 'd2', {
  3226. get() {
  3227. return _d2;
  3228. },
  3229. set(vl) {
  3230. if (vl === _d2)
  3231. return true;
  3232. _d2 = new Proxy(vl, {
  3233. set(target, prop, val) {
  3234. if (['brandingRender', 'dvReveal', '__dv'].includes(prop))
  3235. val = () => null;
  3236. target[prop] = val;
  3237. return true;
  3238. }
  3239. });
  3240. }
  3241. });
  3242. // obfuscated Yandex.Direct
  3243. nt.define('Object.prototype.initYaDirect', undefined);
  3244. }, nullTools, selectiveCookies);
  3245. },
  3246.  
  3247. 'eurogamer.tld': {
  3248. other: 'metabomb.net, usgamer.net',
  3249. now: () => scriptLander(() => {
  3250. abortExecution.inlineScript('_sp_');
  3251. selectiveCookies('sp');
  3252. }, selectiveCookies, abortExecution)
  3253. },
  3254.  
  3255. 'fastpic.ru': () => {
  3256. // Had to obfuscate property name to avoid triggering anti-obfuscation on greasyfork.org -_- (Exception 403012)
  3257. nt.define(`_0x${'4955'}`, []);
  3258. },
  3259.  
  3260. 'fishki.net': () => {
  3261. scriptLander(() => {
  3262. const fishki = {};
  3263. const adv = nt.proxy({
  3264. afterAdblockCheck: nt.func(null, 'fishki.afterAdblockCheck'),
  3265. refreshFloat: nt.func(null, 'fishki.refreshFloat')
  3266. });
  3267. nt.defineOn(fishki, 'adv', adv, 'fishki.');
  3268. nt.defineOn(fishki, 'is_adblock', false, 'fishki.');
  3269. nt.define('fishki', fishki);
  3270. nt.define('Object.prototype.detect', nt.func(undefined, 'detect'));
  3271. win.Object.defineProperty = new Proxy(win.Object.defineProperty, {
  3272. apply(fun, that, args) {
  3273. if (['is_adblock', 'adv'].includes(args[1]) || args[0] === adv)
  3274. return;
  3275. return _apply(fun, that, args);
  3276. }
  3277. });
  3278. }, nullTools);
  3279. gardener('.drag_list > .drag_element, .list-view > .paddingtop15, .post-wrap', /543769|Новости\sпартнеров|Полезная\sреклама/);
  3280. },
  3281.  
  3282. 'forbes.com': () => {
  3283. createStyle(['fbs-ad[ad-id], .top-ad-container, .fbs-ad-wrapper, .footer-ad-labeling, .ad-rail, .ad-unit { display: none !important; }']);
  3284. nt.define('Object.prototype.isAdLight', true);
  3285. nt.define('Object.prototype.initializeAd', nt.func(undefined, '?.initializeAd'));
  3286. win.getComputedStyle = new Proxy(win.getComputedStyle, {
  3287. apply(fun, that, args) {
  3288. let res = _apply(fun, that, args);
  3289. if (res.display === 'none')
  3290. nt.defineOn(res, 'display', 'block', 'getComputedStyle().');
  3291. if (res.visibility === 'hidden')
  3292. nt.defineOn(res, 'visibility', 'visible', 'getComputedStyle().');
  3293. return res;
  3294. }
  3295. });
  3296. win.CSSStyleDeclaration.prototype.getPropertyValue = new Proxy(win.CSSStyleDeclaration.prototype.getPropertyValue, {
  3297. apply(fun, that, args) {
  3298. let res = _apply(fun, that, args);
  3299. if (args[0] === 'display' && res === 'none')
  3300. return 'block';
  3301. if (args[0] === 'visibility' && res === 'hidden')
  3302. return 'visible';
  3303. return res;
  3304. }
  3305. });
  3306. },
  3307.  
  3308. 'freeopenvpn.org': () => {
  3309. const alterEval = Function.constructor;
  3310. win.addEventListener = new Proxy(win.addEventListener, {
  3311. apply(fun, that, args) {
  3312. let [event, callback] = args;
  3313. if (event === 'load') {
  3314. let str = _toString(callback);
  3315. if (/\.clientHeight\s*!=/.test(str))
  3316. args[1] = () => alterEval(
  3317. str.replace(/^function\s*\(\)/, 'function pwd()')
  3318. .replace(/if[^\r\n]*clientHeight[^\r\n]*\)\s*{/, 'if (false) {') + ' pwd();'
  3319. )();
  3320. }
  3321. return _apply(fun, that, args);
  3322. }
  3323. });
  3324. },
  3325.  
  3326. 'friends.in.ua': () => scriptLander(() => {
  3327. Object.defineProperty(win, 'need_warning', {
  3328. get() {
  3329. return 0;
  3330. },
  3331. set() {}
  3332. });
  3333. }),
  3334.  
  3335. 'gamerevolution.com': () => {
  3336. const _clientHeight = Object.getOwnPropertyDescriptor(_Element, 'clientHeight');
  3337. _clientHeight.get = new Proxy(_clientHeight.get, {
  3338. apply(...args) {
  3339. return _apply(...args) || 1;
  3340. }
  3341. });
  3342. Object.defineProperty(_Element, 'clientHeight', _clientHeight);
  3343.  
  3344. const toReplace = [
  3345. 'blockerDetected', 'disableDetected', 'hasAdBlocker',
  3346. 'hasBlockerFlag', 'hasDisabledAdBlocker', 'hasBlocker'
  3347. ];
  3348. win.Object.defineProperty = new Proxy(win.Object.defineProperty, {
  3349. apply(fun, that, args) {
  3350. if (toReplace.includes(args[1])) {
  3351. args[2] = {
  3352. value() {
  3353. return false;
  3354. }
  3355. };
  3356. console.log(args);
  3357. }
  3358. return _apply(fun, that, args);
  3359. }
  3360. });
  3361. },
  3362.  
  3363. 'gamersheroes.com': () => abortExecution.inlineScript('document.createElement', {
  3364. pattern: /window\[\w+\(\[(\d+,?\s?)+\],\s?\w+\)\]/
  3365. }),
  3366.  
  3367. 'gidonline.club': () => createStyle('.tray > div[style] {display: none!important}'),
  3368.  
  3369. 'glav.su': () => scriptLander(() => {
  3370. abortExecution.onSet('abd');
  3371. abortExecution.onSet('script1');
  3372. }, abortExecution),
  3373.  
  3374. 'gorodrabot.ru': () => scriptLander(() => {
  3375. abortExecution.onGet('Object.prototype.yaads');
  3376. abortExecution.onGet('Object.prototype.initYaDirect');
  3377. }, abortExecution),
  3378.  
  3379. 'hdgo.cc': {
  3380. other: '46.30.43.38, couber.be',
  3381. now() {
  3382. (new MutationObserver(
  3383. ms => {
  3384. let m, node;
  3385. for (m of ms)
  3386. for (node of m.addedNodes)
  3387. if (node.tagName instanceof HTMLScriptElement && _getAttribute(node, 'onerror') !== null)
  3388. node.removeAttribute('onerror');
  3389. }
  3390. )).observe(_document.documentElement, {
  3391. childList: true,
  3392. subtree: true
  3393. });
  3394. }
  3395. },
  3396.  
  3397. 'gamepur.com': () => {
  3398. nt.define('ga', nt.func(null, 'ga'));
  3399. win.Object.defineProperty = new Proxy(win.Object.defineProperty, {
  3400. apply(fun, that, args) {
  3401. if (typeof args[1] === 'string' &&
  3402. (args[1] === 'hasAdblocker' || args[1] === 'blockerDetected'))
  3403. throw new TypeError(`Cannot read property '${args[1]}' of undefined`);
  3404. return Reflect.apply(fun, that, args);
  3405. }
  3406. });
  3407. },
  3408.  
  3409. 'hdrezka.ag': () => {
  3410. Object.defineProperty(win, 'ab', {
  3411. value: false,
  3412. enumerable: true
  3413. });
  3414. gardener('div[id][onclick][onmouseup][onmousedown]', /onmouseout/i);
  3415. },
  3416.  
  3417. 'htmlweb.ru': () => {
  3418. let _onerror = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onerror');
  3419. _onerror.set = new Proxy(_onerror.set, {
  3420. apply(fun, that, args) {
  3421. if (that.tagName === 'SCRIPT')
  3422. return _console.log('Skip set onerror for', that);
  3423. return _apply(fun, that, args);
  3424. }
  3425. });
  3426. Object.defineProperty(HTMLElement.prototype, 'onerror', _onerror);
  3427. },
  3428.  
  3429. 'hqq.tv': () => scriptLander(() => {
  3430. // disable anti-debugging in hqq.tv player
  3431. 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);
  3432. deepWrapAPI(root => {
  3433. // skip obfuscated stuff and a few other calls
  3434. let _setInterval = root.setInterval,
  3435. _setTimeout = root.setTimeout;
  3436. root.setInterval = (...args) => {
  3437. let fun = args[0];
  3438. if (typeof fun === 'function') {
  3439. let text = _toString(fun),
  3440. skip = text.includes('check();') || isObfuscated(text);
  3441. _console.trace('setInterval', text, 'skip', skip);
  3442. if (skip) return -1;
  3443. }
  3444. return _setInterval.apply(this, args);
  3445. };
  3446. let wrappedST = new WeakSet();
  3447. root.setTimeout = (...args) => {
  3448. let fun = args[0];
  3449. if (typeof fun === 'function') {
  3450. let text = _toString(fun),
  3451. skip = fun.name === 'check' || isObfuscated(text);
  3452. if (!wrappedST.has(fun)) {
  3453. _console.trace('setTimeout', text, 'skip', skip);
  3454. wrappedST.add(fun);
  3455. }
  3456. if (skip) return;
  3457. }
  3458. return _setTimeout.apply(this, args);
  3459. };
  3460. // skip 'debugger' call
  3461. let _eval = root.eval;
  3462. root.eval = text => {
  3463. if (typeof text === 'string' && text.includes('debugger;')) {
  3464. _console.trace('skip eval', text);
  3465. return;
  3466. }
  3467. _eval(text);
  3468. };
  3469. // Prevent RegExpt + toString trick
  3470. let _proto;
  3471. try {
  3472. _proto = root.RegExp.prototype;
  3473. } catch (ignore) {
  3474. return;
  3475. }
  3476. let _RE_tS = Object.getOwnPropertyDescriptor(_proto, 'toString');
  3477. let _RE_tSV = _RE_tS.value || _RE_tS.get();
  3478. Object.defineProperty(_proto, 'toString', {
  3479. enumerable: _RE_tS.enumerable,
  3480. configurable: _RE_tS.configurable,
  3481. get() {
  3482. return _RE_tSV;
  3483. },
  3484. set(val) {
  3485. _console.trace('Attempt to change toString for', this, 'with', _toString(val));
  3486. }
  3487. });
  3488. });
  3489. }, deepWrapAPI),
  3490.  
  3491. 'hideip.me': {
  3492. now: () => scriptLander(() => {
  3493. let _innerHTML = Object.getOwnPropertyDescriptor(_Element, 'innerHTML');
  3494. let _set_innerHTML = _innerHTML.set;
  3495. let _innerText = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'innerText');
  3496. let _get_innerText = _innerText.get;
  3497. let div = _document.createElement('div');
  3498. _innerHTML.set = function (...args) {
  3499. _set_innerHTML.call(div, args[0].replace('i', 'a'));
  3500. if (args[0] && /[рp][еe]кл/.test(_get_innerText.call(div)) ||
  3501. /(\d\d\d?\.){3}\d\d\d?:\d/.test(_get_innerText.call(this))) {
  3502. _console.log('Anti-Adblock killed.');
  3503. return true;
  3504. }
  3505. _set_innerHTML.apply(this, args);
  3506. };
  3507. Object.defineProperty(_Element, 'innerHTML', _innerHTML);
  3508. Object.defineProperty(win, 'adblock', {
  3509. get() {
  3510. return false;
  3511. },
  3512. set() {},
  3513. enumerable: true
  3514. });
  3515. let _$ = {};
  3516. let _$_map = new WeakMap();
  3517. let _gOPD = Object.getOwnPropertyDescriptor(Object, 'getOwnPropertyDescriptor');
  3518. let _val_gOPD = _gOPD.value;
  3519. _gOPD.value = function (...args) {
  3520. let _res = _val_gOPD.apply(this, args);
  3521. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery')) {
  3522. delete _res.get;
  3523. delete _res.set;
  3524. _res.value = win[args[1]];
  3525. }
  3526. return _res;
  3527. };
  3528. Object.defineProperty(Object, 'getOwnPropertyDescriptor', _gOPD);
  3529. let getJQWrap = (n) => {
  3530. let name = n;
  3531. return {
  3532. enumerable: true,
  3533. get() {
  3534. return _$[name];
  3535. },
  3536. set(x) {
  3537. if (_$_map.has(x)) {
  3538. _$[name] = _$_map.get(x);
  3539. return true;
  3540. }
  3541. if (x === _$.$ || x === _$.jQuery) {
  3542. _$[name] = x;
  3543. return true;
  3544. }
  3545. _$[name] = new Proxy(x, {
  3546. apply(t, o, args) {
  3547. let _res = t.apply(o, args);
  3548. if (_$_map.has(_res.is))
  3549. _res.is = _$_map.get(_res.is);
  3550. else {
  3551. let _is = _res.is;
  3552. _res.is = function (...args) {
  3553. if (args[0] === ':hidden')
  3554. return false;
  3555. return _is.apply(this, args);
  3556. };
  3557. _$_map.set(_is, _res.is);
  3558. }
  3559. return _res;
  3560. }
  3561. });
  3562. _$_map.set(x, _$[name]);
  3563. return true;
  3564. }
  3565. };
  3566. };
  3567. Object.defineProperty(win, '$', getJQWrap('$'));
  3568. Object.defineProperty(win, 'jQuery', getJQWrap('jQuery'));
  3569. let _dP = Object.defineProperty;
  3570. Object.defineProperty = function (...args) {
  3571. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery'))
  3572. return undefined;
  3573. return _dP.apply(this, args);
  3574. };
  3575. })
  3576. },
  3577.  
  3578. 'igra-prestoloff.cx': () => scriptLander(() => {
  3579. /*jslint evil: true */ // yes, evil, I know
  3580. let _write = _document.write.bind(_document);
  3581. /*jslint evil: false */
  3582. nt.define('document.write', t => {
  3583. let id = t.match(/jwplayer\("(\w+)"\)/i);
  3584. if (id && id[1])
  3585. return _write(`<div id="${id[1]}"></div>${t}`);
  3586. return _write('');
  3587. }, {
  3588. enumerable: true
  3589. });
  3590. }),
  3591.  
  3592. 'imageban.ru': () => {
  3593. Object.defineProperty(win, 'V7x1J', {
  3594. get() {
  3595. return null;
  3596. }
  3597. });
  3598. },
  3599.  
  3600. 'inoreader.com': () => scriptLander(() => {
  3601. let i = setInterval(() => {
  3602. if ('adb_detected' in win) {
  3603. win.adb_detected = () => win.adb_not_detected();
  3604. clearInterval(i);
  3605. }
  3606. }, 10);
  3607. _document.addEventListener('DOMContentLoaded', () => clearInterval(i), false);
  3608. }),
  3609.  
  3610. 'it-actual.ru': () => scriptLander(() => {
  3611. abortExecution.onAll('blocked');
  3612. abortExecution.onGet('nsg');
  3613. }, abortExecution),
  3614.  
  3615. 'ivi.ru': () => {
  3616. let _xhr_open = win.XMLHttpRequest.prototype.open;
  3617. win.XMLHttpRequest.prototype.open = function (method, url, ...args) {
  3618. if (typeof url === 'string')
  3619. if (url.endsWith('/track'))
  3620. return;
  3621. return _xhr_open.call(this, method, url, ...args);
  3622. };
  3623. let _responseText = Object.getOwnPropertyDescriptor(XMLHttpRequest.prototype, 'responseText');
  3624. let _responseText_get = _responseText.get;
  3625. _responseText.get = function () {
  3626. if (this.__responseText__)
  3627. return this.__responseText__;
  3628. let res = _responseText_get.apply(this, arguments);
  3629. let o;
  3630. try {
  3631. if (res)
  3632. o = JSON.parse(res);
  3633. } catch (ignore) {}
  3634. let changed = false;
  3635. if (o && o.result) {
  3636. if (o.result instanceof Array &&
  3637. 'adv_network_logo_url' in o.result[0]) {
  3638. o.result = [];
  3639. changed = true;
  3640. }
  3641. if (o.result.show_adv) {
  3642. o.result.show_adv = false;
  3643. changed = true;
  3644. }
  3645. }
  3646. if (changed) {
  3647. _console.log('changed response >>', o);
  3648. res = JSON.stringify(o);
  3649. }
  3650. this.__responseText__ = res;
  3651. return res;
  3652. };
  3653. Object.defineProperty(XMLHttpRequest.prototype, 'responseText', _responseText);
  3654. },
  3655.  
  3656. 'kakprosto.ru': () => scriptLander(() => {
  3657. selectiveCookies('yadb');
  3658. abortExecution.inlineScript('yaProxy', {
  3659. pattern: /yadb/
  3660. });
  3661. abortExecution.inlineScript('yandexContextAsyncCallbacks');
  3662. abortExecution.inlineScript('adfoxAsyncParams');
  3663. abortExecution.inlineScript('adfoxBackGroundLoaded');
  3664. }, selectiveCookies, abortExecution),
  3665.  
  3666. 'kinopoisk.ru': () => {
  3667. // filter cookies
  3668. // set no-branding body style and adjust other blocks on the page
  3669. const style = {
  3670. '.app__header.app__header_margin-bottom_brand, #top': {
  3671. margin_bottom: '20px !important'
  3672. },
  3673. '.app__branding': {
  3674. display: 'none!important'
  3675. }
  3676. };
  3677. if (location.hostname === 'www.kinopoisk.ru' && !location.pathname.startsWith('/games/'))
  3678. style['html:not(#id), body:not(#id), .app-container'] = {
  3679. background: '#d5d5d5 url(/images/noBrandBg.jpg) 50% 0 no-repeat !important'
  3680. };
  3681. createStyle(style);
  3682. scriptLander(() => {
  3683. selectiveCookies('cmtchd|crookie|kpunk');
  3684. // filter JSON
  3685. win.JSON.parse = new Proxy(win.JSON.parse, {
  3686. apply(fun, that, args) {
  3687. let o = _apply(fun, that, args);
  3688. let name = 'antiAdBlockCookieName';
  3689. if (name in o && typeof o[name] === 'string')
  3690. selectiveCookies(o[name]);
  3691. name = 'branding';
  3692. if (name in o) o[name] = {};
  3693. // tricks against ads in the trailer player
  3694. // if (location.hostname.startsWith('widgets.'))
  3695. if (o.page && o.page.playerParams)
  3696. delete o.page.playerParams.adConfig;
  3697. if (o.common && o.common.bunker && o.common.bunker.adv && o.common.bunker.adv.filmIdWithoutAd)
  3698. o.common.bunker.adv.filmIdWithoutAd.includes = () => true;
  3699. //_console.log('JSON.parse', o);
  3700. return o;
  3701. }
  3702. });
  3703. // skip timeout check for blocked requests
  3704. win.setTimeout = new Proxy(win.setTimeout, {
  3705. apply(fun, that, args) {
  3706. if (args[1] === 100) {
  3707. let str = _toString(args[0]);
  3708. if (str.endsWith('{a()}') || str.endsWith('{n()}'))
  3709. return;
  3710. }
  3711. return _apply(fun, that, args);
  3712. }
  3713. });
  3714. // obfuscated Yandex.Direct
  3715. nt.define('Object.prototype.initYaDirect', undefined);
  3716. nt.define('Object.prototype._resolveDetectResult', () => null);
  3717. nt.define('Object.prototype.detectResultPromise', new Promise(r => r(false)));
  3718. if (location.hostname === 'www.kinopoisk.ru')
  3719. nt.define('Object.prototype.initAd', nt.func(undefined, 'initAd'));
  3720. // catch branding and other things
  3721. let _KP;
  3722. Object.defineProperty(win, 'KP', {
  3723. get() {
  3724. return _KP;
  3725. },
  3726. set(val) {
  3727. if (_KP === val)
  3728. return true;
  3729. _KP = new Proxy(val, {
  3730. set(kp, name, val) {
  3731. if (name === 'branding') {
  3732. kp[name] = new Proxy({
  3733. weborama: {}
  3734. }, {
  3735. get(kp, name) {
  3736. return name in kp ? kp[name] : '';
  3737. },
  3738. set() {}
  3739. });
  3740. return true;
  3741. }
  3742. if (name === 'config')
  3743. val = new Proxy(val, {
  3744. set(cfg, name, val) {
  3745. if (name === 'anContextUrl')
  3746. return true;
  3747. if (name === 'adfoxEnabled' || name === 'hasBranding')
  3748. val = false;
  3749. if (name === 'adfoxVideoAdUrls')
  3750. val = {
  3751. flash: {},
  3752. html: {}
  3753. };
  3754. cfg[name] = val;
  3755. return true;
  3756. }
  3757. });
  3758. kp[name] = val;
  3759. return true;
  3760. }
  3761. });
  3762. _console.log('KP =', val);
  3763. }
  3764. });
  3765. }, selectiveCookies, nullTools);
  3766. },
  3767.  
  3768. 'korrespondent.net': {
  3769. now: () => scriptLander(() => {
  3770. nt.define('holder', function (id) {
  3771. let div = _document.getElementById(id);
  3772. if (!div)
  3773. return;
  3774. if (div.parentNode.classList.contains('col__sidebar')) {
  3775. div.parentNode.appendChild(div);
  3776. div.style.height = '300px';
  3777. }
  3778. });
  3779. }, nullTools),
  3780. dom() {
  3781. for (let frame of _document.querySelectorAll('.unit-side-informer > iframe'))
  3782. frame.parentNode.style.width = '1px';
  3783. }
  3784. },
  3785.  
  3786. 'libertycity.ru': () => scriptLander(() => {
  3787. nt.define('adBlockEnabled', false);
  3788. }, nullTools),
  3789.  
  3790. 'liveinternet.ru': () => scriptLander(() => {
  3791. abortExecution.onGet('Object.prototype.initAd');
  3792. }, abortExecution),
  3793.  
  3794. 'livejournal.com': () => scriptLander(() => {
  3795. nt.define('Object.prototype.Adf', undefined);
  3796. nt.define('Object.prototype.Begun', undefined);
  3797. }, nullTools),
  3798.  
  3799. 'mail.ru': {
  3800. other: 'ok.ru, sportmail.ru',
  3801. now: () => scriptLander(() => {
  3802. const _hostparts = location.hostname.split('.');
  3803. const _subdomain = _hostparts.slice(-3).join('.');
  3804. const _hostname = _hostparts.slice(-2).join('.');
  3805. const _emailru = _subdomain === 'e.mail.ru' || _subdomain === 'octavius.mail.ru';
  3806. const _mymailru = _subdomain === 'my.mail.ru';
  3807. const _otvet = _subdomain === 'otvet.mail.ru';
  3808. const _okru = _hostname === 'ok.ru';
  3809. // setTimeout filter
  3810. // advBlock|rbParams - ads
  3811. // document\.title= - blinking title on background news load on main page
  3812. const pattern = /advBlock|rbParams|document\.title=/i;
  3813. const _setTimeout = win.setTimeout;
  3814. win.setTimeout = function setTimeout(...args) {
  3815. let text = _toString(args[0]);
  3816. if (pattern.test(text)) {
  3817. _console.trace('Skipped setTimeout:', text);
  3818. return;
  3819. }
  3820. return _setTimeout(...args);
  3821. };
  3822.  
  3823. // Trick to prevent mail.ru from removing 3rd-party styles
  3824. nt.define('Object.prototype.restoreVisibility', nt.func(null, 'restoreVisibility'));
  3825. // Other Yandex Direct and other ads
  3826. nt.define('Object.prototype.initMimic', undefined);
  3827. nt.define('Object.prototype.hpConfig', undefined);
  3828. if (!_otvet) // used for a different purpose there
  3829. nt.define('Object.prototype.direct', undefined);
  3830. const getAds = () => new Promise(
  3831. r => r(nt.proxy({}, '?.getAds()'))
  3832. );
  3833. nt.define('Object.prototype.getAds', getAds);
  3834. nt.define('rb_counter', nt.func(null, 'rb_counter'));
  3835. if (_subdomain === 'mail.ru') { // main page
  3836. nt.define('Object.prototype.baits', undefined); // detector
  3837. nt.define('Object.prototype.getFeed', nt.func(null, 'pulse.getFeed')); // Pulse feed
  3838. createStyle('body > div > .pulse { display: none !important }');
  3839. }
  3840. if (_emailru)
  3841. nt.define('Object.prototype.show_me_ads', undefined);
  3842. else if (_mymailru)
  3843. nt.define('Object.prototype.runMimic', nt.func(null, 'runMimic'));
  3844. else {
  3845. nt.define('Object.prototype.mimic', undefined);
  3846. const xray = nt.func(undefined, 'xray');
  3847. nt.defineOn(xray, 'send', nt.func(undefined, 'xray.send'), 'xray.');
  3848. nt.defineOn(xray, 'radarPrefix', null, 'xray.');
  3849. nt.defineOn(xray, 'xrayRadarUrl', undefined, 'xray.');
  3850. nt.defineOn(xray, 'defaultParams', nt.proxy({
  3851. i: undefined,
  3852. p: 'media'
  3853. }), 'xray.');
  3854. nt.defineOn(xray, 'getConfig', nt.func(
  3855. nt.proxy({
  3856. radarPrefix: 'dev'
  3857. }, 'xray.getConfig().'),
  3858. 'xray.getConfig'
  3859. ));
  3860. nt.define('Object.prototype.xray', nt.proxy(xray));
  3861. }
  3862. // shenanigans against ok.ru ABP detector
  3863. if (_okru) {
  3864. abortExecution.onGet('OK.hooks');
  3865. // banners on ok.ru and counter
  3866. nt.define('getAdvTargetParam', nt.func(null, 'getAdvTargetParam'));
  3867. // break detection in case detector wasn't wrapped
  3868. abortExecution.onSet('Object.prototype.adBlockDetected');
  3869. }
  3870. // news.mail.ru and sportmail.ru
  3871. abortExecution.onGet('myWidget');
  3872. // cleanup e.mail.ru configs and mimic config on news and sport
  3873. const emptyString = (root, name) => root[name] && (root[name] = '');
  3874. const detectMimic = /direct|240x400|SlotView/;
  3875. win.JSON.parse = new Proxy(win.JSON.parse, {
  3876. apply(fun, that, args) {
  3877. let o = _apply(fun, that, args);
  3878. if (o && typeof o === 'object') {
  3879. if (o.cfg && o.cfg.sotaFeatures) {
  3880. let root = o.cfg.sotaFeatures;
  3881. if (Array.isArray(root.adv)) root.adv = [];
  3882. for (let name in root)
  3883. if (name.startsWith('adv-') || name.startsWith('adman-'))
  3884. delete root[name];
  3885. ['email_logs_to', 'smokescreen-locators'].forEach(name => emptyString(root, name));
  3886. }
  3887. if (o.userConfig) {
  3888. if (Array.isArray(o.userConfig.honeypot))
  3889. o.userConfig.honeypot.forEach((v, id, me) => (me[id] = []));
  3890. const cfg = o.userConfig.config;
  3891. if (cfg && cfg.honeypot)
  3892. emptyString(cfg.honeypot, 'baits');
  3893. }
  3894. if (o.body) {
  3895. const flags = o.body.common_purpose_flags;
  3896. if (flags && 'hide_ad_in_mail_web' in flags)
  3897. flags.hide_ad_in_mail_web = true;
  3898. if (o.body.show_me_ads)
  3899. o.body.show_me_ads = false;
  3900. }
  3901. //_console.log('JSON.parse', o);
  3902. }
  3903. if (Array.isArray(o))
  3904. if (o.some(t => typeof t === 'string' && detectMimic.test(t))) {
  3905. _console.log('Replaced', o);
  3906. o = [];
  3907. } //else _console.log('JSON.parse', o);
  3908. return o;
  3909. }
  3910. });
  3911. // all the rest is only needed on main page and in emails
  3912. if (_subdomain !== 'mail.ru' && !_emailru && !_okru)
  3913. return;
  3914.  
  3915. // Disable page scrambler on mail.ru to let extensions easily block ads there
  3916. let logger = {
  3917. apply(fun, that, args) {
  3918. let res = _apply(fun, that, args);
  3919. _console.log(`${fun._name}(`, ...args, `)\n>>`, res);
  3920. return res;
  3921. }
  3922. };
  3923.  
  3924. function wrapLocator(locator) {
  3925. if ('setup' in locator) {
  3926. let _setup = locator.setup;
  3927. locator.setup = function (o) {
  3928. if ('enable' in o) {
  3929. o.enable = false;
  3930. _console.log('Disable mimic mode.');
  3931. }
  3932. if ('links' in o) {
  3933. o.links = [];
  3934. _console.log('Call with empty list of sheets.');
  3935. }
  3936. return _setup.call(this, o);
  3937. };
  3938. locator.insertSheet = () => false;
  3939. locator.wrap = () => false;
  3940. }
  3941. try {
  3942. let names = [];
  3943. for (let name in locator)
  3944. if (typeof locator[name] === 'function' && name !== 'transform') {
  3945. locator[name]._name = "locator." + name;
  3946. locator[name] = new Proxy(locator[name], logger);
  3947. names.push(name);
  3948. }
  3949. _console.log(`[locator] wrapped properties: ${names.length ? names.join(', ') : '[empty]'}`);
  3950. } catch (e) {
  3951. _console.log(e);
  3952. }
  3953. return locator;
  3954. }
  3955.  
  3956. function defineLocator(root) {
  3957. let _locator = root.locator;
  3958. let wrapLocatorSetter = vl => _locator = wrapLocator(vl);
  3959. let loc_desc = Object.getOwnPropertyDescriptor(root, 'locator');
  3960. if (!loc_desc || loc_desc.set !== wrapLocatorSetter)
  3961. try {
  3962. Object.defineProperty(root, 'locator', {
  3963. set: wrapLocatorSetter,
  3964. get() {
  3965. return _locator;
  3966. }
  3967. });
  3968. } catch (err) {
  3969. _console.log('Unable to redefine "locator" object!!!', err);
  3970. }
  3971. if (loc_desc.value)
  3972. _locator = wrapLocator(loc_desc.value);
  3973. }
  3974.  
  3975. { // auto-stubs for various ad, detection and obfuscation modules
  3976. const missingCheck = {
  3977. get(obj, name) {
  3978. let res = obj[name];
  3979. if (!(name in obj))
  3980. _console.trace(`Missing "${name}" in`, obj);
  3981. return res;
  3982. }
  3983. };
  3984. const skipLog = (name, ret) => (...args) => (_console.log(`${name}(`, ...args, ')'), ret);
  3985. const createSkipAllObject = (baseName, obj = {
  3986. __esModule: true
  3987. }) => new Proxy(obj, {
  3988. get(obj, name) {
  3989. if (name in obj)
  3990. return obj[name];
  3991. _console.log(`Created stub for "${name}" in ${baseName}.`);
  3992. obj[name] = skipLog(`${baseName}.${name}`);
  3993. return obj[name];
  3994. },
  3995. set() {}
  3996. });
  3997. const redefiner = {
  3998. apply(fun, that, args) {
  3999. let res;
  4000. let warn = false;
  4001. let name = fun._name;
  4002. if (name === 'mrg-smokescreen/Welter')
  4003. res = {
  4004. isWelter() {
  4005. return true;
  4006. },
  4007. wrap: skipLog(`${name}.wrap`)
  4008. };
  4009. if (name === 'mrg-smokescreen/Honeypot')
  4010. res = {
  4011. check(...args) {
  4012. _console.log(`${name}.check(`, ...args, ')');
  4013. return new Promise(() => undefined);
  4014. },
  4015. version: "-1"
  4016. };
  4017. if (name === 'advert/adman/adman') {
  4018. let features = {
  4019. siteZones: {},
  4020. slots: {}
  4021. };
  4022. [
  4023. 'expId', 'siteId', 'mimicEndpoint', 'mimicPartnerId',
  4024. 'immediateFetchTimeout', 'delayedFetchTimeout'
  4025. ].forEach(name => void(features[name] = null));
  4026. res = createSkipAllObject(name, {
  4027. getFeatures: skipLog(`${name}.getFeatures`, features)
  4028. });
  4029. }
  4030. if (name === 'mrg-smokescreen/Utils')
  4031. res = createSkipAllObject(name, {
  4032. extend(...args) {
  4033. let res = {
  4034. enable: false,
  4035. match: [],
  4036. links: []
  4037. };
  4038. _console.log(`${name}.extend(`, ...args, ') >>', res);
  4039. return res;
  4040. }
  4041. });
  4042. if (name.startsWith('OK/banners/') ||
  4043. name.startsWith('mrg-smokescreen/StyleSheets') ||
  4044. name === '@mail/mimic' ||
  4045. name === 'mediator/advert-managers')
  4046. res = createSkipAllObject(name);
  4047. if (res) {
  4048. Object.defineProperty(res, Symbol.toStringTag, {
  4049. get() {
  4050. return `Skiplog object for ${name}`;
  4051. }
  4052. });
  4053. Object.defineProperty(res, Symbol.toPrimitive, {
  4054. value(hint) {
  4055. if (hint === 'string')
  4056. return Object.prototype.toString.call(this);
  4057. return `[missing toPrimitive] ${name} ${hint}`;
  4058. }
  4059. });
  4060. res = new Proxy(res, missingCheck);
  4061. } else {
  4062. res = _apply(fun, that, args);
  4063. warn = true;
  4064. }
  4065. _console[warn ? 'warn' : 'log'](name, '(', ...args, ')\n>>', res);
  4066. return res;
  4067. }
  4068. };
  4069.  
  4070. const advModuleNamesStartWith = /^(mrg-(context|honeypot)|adv\/)/;
  4071. const advModuleNamesGeneric = /advert|banner|mimic|smoke/i;
  4072. const wrapAdFuncs = {
  4073. apply(fun, that, args) {
  4074. let module = args[0];
  4075. if (typeof module === 'string')
  4076. if ((advModuleNamesStartWith.test(module) ||
  4077. advModuleNamesGeneric.test(module)) &&
  4078. // fix for e.mail.ru in Fx56 and below, looks like Proxy is quirky there
  4079. !module.startsWith('patron.v2.')) {
  4080. let main = args[args.length - 1];
  4081. main._name = module;
  4082. args[args.length - 1] = new Proxy(main, redefiner);
  4083. }
  4084. return _apply(fun, that, args);
  4085. }
  4086. };
  4087. const wrapDefine = def => {
  4088. if (!def)
  4089. return;
  4090. _console.log('define =', def);
  4091. def = new Proxy(def, wrapAdFuncs);
  4092. def._name = 'define';
  4093. return def;
  4094. };
  4095. let _define = wrapDefine(win.define);
  4096. Object.defineProperty(win, 'define', {
  4097. get() {
  4098. return _define;
  4099. },
  4100. set(x) {
  4101. if (_define === x)
  4102. return true;
  4103. _define = wrapDefine(x);
  4104. return true;
  4105. }
  4106. });
  4107. }
  4108.  
  4109. let _honeyPot;
  4110.  
  4111. function defineDetector(mr) {
  4112. let __ = mr._ || {};
  4113. let setHoneyPot = o => {
  4114. if (!o || o === _honeyPot) return;
  4115. _console.log('[honeyPot]', o);
  4116. _honeyPot = function () {
  4117. this.check = new Proxy(() => {
  4118. __.STUCK_IN_POT = false;
  4119. return false;
  4120. }, logger);
  4121. this.check._name = 'honeyPot.check';
  4122. this.destroy = () => null;
  4123. };
  4124. };
  4125. if ('honeyPot' in mr)
  4126. setHoneyPot(mr.honeyPot);
  4127. else
  4128. Object.defineProperty(mr, 'honeyPot', {
  4129. get() {
  4130. return _honeyPot;
  4131. },
  4132. set: setHoneyPot
  4133. });
  4134.  
  4135. __ = new Proxy(__, {
  4136. get(target, prop) {
  4137. return target[prop];
  4138. },
  4139. set(target, prop, val) {
  4140. _console.log(`mr._.${prop} =`, val);
  4141. target[prop] = val;
  4142. return true;
  4143. }
  4144. });
  4145. mr._ = __;
  4146. }
  4147.  
  4148. function defineAdd(mr) {
  4149. let _add;
  4150. let addWrapper = {
  4151. apply(fun, that, args) {
  4152. let module = args[0];
  4153. if (typeof module === 'string' && module.startsWith('ad')) {
  4154. _console.log('Skip module:', module);
  4155. return;
  4156. }
  4157. if (typeof module === 'object' && module.name.startsWith('ad'))
  4158. _console.log('Loaded module:', module);
  4159. return logger.apply(fun, that, args);
  4160. }
  4161. };
  4162. let setMrAdd = v => {
  4163. if (!v) return;
  4164. v._name = 'mr.add';
  4165. v = new Proxy(v, addWrapper);
  4166. _add = v;
  4167. };
  4168. if ('add' in mr)
  4169. setMrAdd(mr.add);
  4170. Object.defineProperty(mr, 'add', {
  4171. get() {
  4172. return _add;
  4173. },
  4174. set: setMrAdd
  4175. });
  4176.  
  4177. }
  4178.  
  4179. const _mr_wrapper = vl => {
  4180. defineLocator(vl.mimic ? vl.mimic : vl);
  4181. defineDetector(vl);
  4182. defineAdd(vl);
  4183. return vl;
  4184. };
  4185. if ('mr' in win) {
  4186. _console.log('Found existing "mr" object.');
  4187. win.mr = _mr_wrapper(win.mr);
  4188. } else {
  4189. let _mr;
  4190. Object.defineProperty(win, 'mr', {
  4191. get() {
  4192. return _mr;
  4193. },
  4194. set(vl) {
  4195. _mr = vl ? _mr_wrapper(vl) : vl;
  4196. },
  4197. configurable: true
  4198. });
  4199. let _defineProperty = _bindCall(Object.defineProperty);
  4200. Object.defineProperty = function defineProperty(...args) {
  4201. const [obj, name, conf] = args;
  4202. if (name === 'mr' && obj instanceof Window) {
  4203. _console.trace('Object.defineProperty(', ...args, ')');
  4204. conf.set(_mr_wrapper(conf.get()));
  4205. }
  4206. if ((name === 'honeyPot' || name === 'add') && _mr === obj && conf.set)
  4207. return;
  4208. return _defineProperty(this, ...args);
  4209. };
  4210. }
  4211. }, nullTools, selectiveCookies, abortExecution)
  4212. },
  4213.  
  4214. 'oms.matchat.online': () => scriptLander(() => {
  4215. let _rmpGlobals;
  4216. Object.defineProperty(win, 'rmpGlobals', {
  4217. get() {
  4218. return _rmpGlobals;
  4219. },
  4220. set(val) {
  4221. if (val === _rmpGlobals)
  4222. return true;
  4223. _rmpGlobals = new Proxy(val, {
  4224. get(obj, name) {
  4225. if (name === 'adBlockerDetected')
  4226. return false;
  4227. return obj[name];
  4228. },
  4229. set(obj, name, val) {
  4230. if (name === 'adBlockerDetected')
  4231. _console.trace('rmpGlobals.adBlockerDetected =', val);
  4232. else
  4233. obj[name] = val;
  4234. return true;
  4235. }
  4236. });
  4237. }
  4238. });
  4239. }),
  4240.  
  4241. 'megogo.net': {
  4242. now() {
  4243. nt.define('adBlock', false);
  4244. nt.define('showAdBlockMessage', nt.func(null, 'showAdBlockMessage'));
  4245. }
  4246. },
  4247.  
  4248. 'naruto-base.su': () => gardener('div[id^="entryID"],.block', /href="http.*?target="_blank"/i),
  4249.  
  4250. 'otzovik.com': () => scriptLander(() => {
  4251. abortExecution.onAll('Object.prototype.getYa');
  4252. abortExecution.onGet('Object.prototype.parseServerDataFunction');
  4253. let _o_math = win.o_math;
  4254. Object.defineProperty(win, 'o_math', {
  4255. get() {
  4256. return _o_math;
  4257. },
  4258. set(val) {
  4259. delete val.ext_uid;
  4260. _o_math = val;
  4261. throw removeOwnFootprint(new ReferenceError('fetch is not defined'));
  4262. }
  4263. });
  4264. }, abortExecution, selectiveCookies),
  4265.  
  4266. 'overclockers.ru': {
  4267. now() {
  4268. abortExecution.onAll('cardinals');
  4269. abortExecution.inlineScript('Document.prototype.createElement', {
  4270. pattern: /mamydirect/
  4271. });
  4272. }
  4273. },
  4274.  
  4275. 'peka2.tv': () => {
  4276. let bodyClass = 'body--branding';
  4277. let checkNode = node => {
  4278. for (let className of node.classList)
  4279. if (className.includes('banner') || className === bodyClass) {
  4280. _removeAttribute(node, 'style');
  4281. node.classList.remove(className);
  4282. for (let attr of Array.from(node.attributes))
  4283. if (attr.name.startsWith('advert'))
  4284. _removeAttribute(node, attr.name);
  4285. }
  4286. };
  4287. (new MutationObserver(ms => {
  4288. let m, node;
  4289. for (m of ms)
  4290. for (node of m.addedNodes)
  4291. if (node instanceof HTMLElement)
  4292. checkNode(node);
  4293. })).observe(_de, {
  4294. childList: true,
  4295. subtree: true
  4296. });
  4297. (new MutationObserver(ms => {
  4298. for (let m of ms)
  4299. checkNode(m.target);
  4300. })).observe(_de, {
  4301. attributes: true,
  4302. subtree: true,
  4303. attributeFilter: ['class']
  4304. });
  4305. },
  4306.  
  4307. 'pikabu.ru': () => gardener('.story', /story__author[^>]+>ads</i, {
  4308. root: '.inner_wrap',
  4309. observe: true
  4310. }),
  4311.  
  4312. 'piratbit.tld': {
  4313. other: 'pb.wtf',
  4314. dom() {
  4315. const remove = node => node && node.parentNode && (_console.log('removed', node), node.parentNode.removeChild(node));
  4316. const isAdLink = el => location.hostname === el.hostname && /^\/(\w{3}|exit|out)\/[\w=/]{20,}$/.test(el.pathname);
  4317. // line above topic content and images in the slider in the header
  4318. for (let el of _document.querySelectorAll('.releas-navbar div a, #page_contents a'))
  4319. if (isAdLink(el))
  4320. remove(el.closest('tr[class]:not(.top_line):not(.active), .row2[id^="post_"]') || el.closest('div[style]:not(.row1):not(.btn-group)'));
  4321. }
  4322. },
  4323.  
  4324. 'pixelexperience.org': () => scriptLander(() => {
  4325. abortExecution.inlineScript('eval', {
  4326. pattern: /blockadblock/
  4327. });
  4328. }, abortExecution),
  4329.  
  4330. 'player.starlight.digital': {
  4331. other: 'teleportal.ua',
  4332. dom() {
  4333. scriptLander(() => {
  4334. let _currVideo = win.currVideo;
  4335. Object.defineProperty(win, 'currVideo', {
  4336. get() {
  4337. return _currVideo;
  4338. },
  4339. set(val) {
  4340. _console.log('currVideo =', val);
  4341. if ('adv' in val)
  4342. val.adv.creatives = [];
  4343. if ('showadv' in val)
  4344. val.showadv = false;
  4345. if ('mediaHls' in val)
  4346. val.mediaHls = val.mediaHls.replace('adv=1', 'adv=0');
  4347. if ('media' in val)
  4348. for (let media of val.media)
  4349. media.url = media.url.replace('adv=1', 'adv=0');
  4350. _currVideo = val;
  4351. }
  4352. });
  4353. nt.define('Object.prototype.isAdBlockEnabled', false);
  4354. nt.define('Object.prototype.AdBlockDynamicConfig', undefined);
  4355. nt.define('ADT_PLAYER_ADBLOCK_CONFIG', '');
  4356. nt.define('ADT_PLAYER_ADBLOCK_CONFIG_DETECT_ON_FAIL', false);
  4357. }, nullTools);
  4358. }
  4359. },
  4360.  
  4361. 'player.vgtrk.com': () => nt.define('Object.prototype.CheckAuth', nt.func(undefined, '?.CheckAuth')),
  4362.  
  4363. 'qrz.ru': {
  4364. now() {
  4365. nt.define('ab', false);
  4366. nt.define('tryMessage', nt.func(null, 'tryMessage'));
  4367. }
  4368. },
  4369.  
  4370. 'rambler.ru': {
  4371. other: [
  4372. 'afisha.ru', 'autorambler.ru', 'championat.com', 'eda.ru', 'gazeta.ru', 'lenta.ru', 'letidor.ru',
  4373. 'media.eagleplatform.com', 'motor.ru', 'passion.ru', 'quto.ru', 'rns.online', 'wmj.ru'
  4374. ].join(','),
  4375. now() {
  4376. scriptLander(() => {
  4377. // Skip login form and frames, and comments frames. Nothing to do here.
  4378. if (['id.rambler.ru', 'comments.rambler.ru'].includes(location.hostname))
  4379. return;
  4380.  
  4381. // prevent autoplay
  4382. if (location.hostname === 'vp.rambler.ru') {
  4383. nt.define('Object.prototype.minPlayingVisibleHeight', Number.MAX_SAFE_INTEGER);
  4384. return;
  4385. }
  4386. if (location.hostname.endsWith('.media.eagleplatform.com')) {
  4387. const _stopImmediatePropagation = _bindCall(Event.prototype.stopImmediatePropagation);
  4388. win.addEventListener('message', e => {
  4389. if (typeof e.data === 'object' && e.data.visible)
  4390. _stopImmediatePropagation(e);
  4391. });
  4392. return;
  4393. }
  4394. /* jshint -W001 */ // aka 'hasOwnProperty' is a really bad name, but this is a wrapper
  4395. const autoList = new Set(['autoplay', 'scrollplay']);
  4396. win.Object.prototype.hasOwnProperty = new Proxy(win.Object.prototype.hasOwnProperty, {
  4397. apply(fun, that, args) {
  4398. if (autoList.has(args[0]))
  4399. return false;
  4400. return _apply(fun, that, args);
  4401. }
  4402. });
  4403. /* jshint +W001 */
  4404.  
  4405. selectiveCookies('detect_count|dv|dvr|lv|lvr');
  4406. // Wrapper for adv loader settings in QW50aS1BZEJsb2Nr['7t7hystz']
  4407. const _contexts = new WeakMap();
  4408. Object.defineProperty(Object.prototype, 'Settings', {
  4409. set(val) {
  4410. if (typeof val === 'object' && 'Transports' in val && 'Urls' in val)
  4411. val.Urls = [];
  4412. _contexts.set(this, val);
  4413. },
  4414. get() {
  4415. return _contexts.get(this);
  4416. }
  4417. });
  4418. // disable video pop-outs in articles on gazeta.ru
  4419. if (location.hostname === 'gazeta.ru' || location.hostname.endsWith('.gazeta.ru'))
  4420. nt.define('creepyVideo', nt.func(null, 'creepyVideo'));
  4421. // disable Alice popup (encountered on horoscopes.rambler.ru)
  4422. nt.define('Object.prototype.needShowAlicePopup', false);
  4423. // disable some logging
  4424. yandexRavenStub();
  4425. // hide "disable ads" button
  4426. createStyle('a[href^="https://prime.rambler.ru/promo/"] { display: none !important }');
  4427. // prevent ads from loading
  4428. abortExecution.onGet('g_GazetaNoExchange');
  4429.  
  4430. //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;
  4431. const scriptSkipList = /nrWrapper|\/(desktopVendor|vendorsDesktop)\.|<anonymous>/;
  4432. const isLocalScript = (log) => {
  4433. let e = removeOwnFootprint(new Error()),
  4434. parts = e.stack.split(/\n/),
  4435. row = 0;
  4436. if (!/http/.test(parts[row]))
  4437. row += 1;
  4438. while (scriptSkipList.test(parts[row]))
  4439. row += 1;
  4440. let parse = /(https?:.*):\d+:\d+/.exec(parts[row]);
  4441. if (log)
  4442. _console.log(parse && parse[1] === location.href, parts[row], [parts]);
  4443. return parse && parse[1] === location.href;
  4444. };
  4445. const cutoff = 200;
  4446. const fts = f => _toString(f.__sentry__ && f.__sentry_original__ || f['nr@original'] || f);
  4447. win.setTimeout = new Proxy(win.setTimeout, {
  4448. apply(fun, that, args) {
  4449. if (isLocalScript()) {
  4450. const [callback, delay] = args;
  4451. const str = fts(callback);
  4452. if (!/\n/.test(str)) {
  4453. _console.trace(`Skipped setTimeout(${str.slice(0, cutoff)}${str.length > cutoff ? '\u2026' : ''}, ${delay})`);
  4454. return null;
  4455. }
  4456. }
  4457. return _apply(fun, that, args);
  4458. }
  4459. });
  4460. const _onerror = Object.getOwnPropertyDescriptor(win.HTMLElement.prototype, 'onerror');
  4461. _onerror.set = new Proxy(_onerror.set, {
  4462. apply(fun, that, args) {
  4463. if (typeof args[0] === 'function' && isLocalScript()) {
  4464. const str = fts(args[0]);
  4465. _console.trace(`Skipped onerror = ${str.slice(0, cutoff)}${str.length > cutoff ? '\u2026' : ''}`);
  4466. return;
  4467. }
  4468. return _apply(fun, that, args);
  4469. }
  4470. });
  4471. Object.defineProperty(win.HTMLElement.prototype, 'onerror', _onerror);
  4472. // Skip dev console check
  4473. win.console.debug = new Proxy(win.console.debug, {
  4474. apply(fun, that, args) {
  4475. if (args[0] instanceof HTMLImageElement)
  4476. return;
  4477. return _apply(fun, that, args);
  4478. }
  4479. });
  4480. // anti-abdetector
  4481. let _primeStorage;
  4482. Object.defineProperty(win, 'primeStorage', {
  4483. get() {
  4484. if (isLocalScript())
  4485. throw removeOwnFootprint(new TypeError(`Cannot read property 'primeStorage' of undefined`));
  4486. return _primeStorage;
  4487. },
  4488. set(val) {
  4489. _primeStorage = val;
  4490. }
  4491. });
  4492. // Defense against triggered detector
  4493. _Node.removeChild = new Proxy(_Node.removeChild, {
  4494. apply(fun, that, args) {
  4495. const [el] = args;
  4496. if (el.tagName === 'LINK' && isLocalScript()) {
  4497. _console.log(`Let's not remove ${el.tagName}.`);
  4498. return;
  4499. }
  4500. return _apply(fun, that, args);
  4501. }
  4502. });
  4503. }, nullTools, yandexRavenStub, selectiveCookies, abortExecution);
  4504. },
  4505. dom() {
  4506. // disable video pop-outs in articles on lenta.ru and rambler.ru
  4507. let domain = location.hostname.split('.');
  4508. if (['lenta', 'rambler'].includes(domain[domain.length - 2])) {
  4509. const player = _document.querySelector('.js-video-box__container, .j-mini-player__video');
  4510. if (player) player.removeAttribute('class');
  4511. }
  4512. // remove utm_ form links
  4513. const parser = _document.createElement('a');
  4514. _document.addEventListener('mousedown', (e) => {
  4515. let t = e.target;
  4516. if (!t.href)
  4517. t = t.closest('A');
  4518. if (t && t.href) {
  4519. parser.href = t.href;
  4520. let remove = [];
  4521. let params = parser.search.slice(1).split('&').filter(name => {
  4522. if (name.startsWith('utm_')) {
  4523. remove.push(name);
  4524. return false;
  4525. }
  4526. return true;
  4527. });
  4528. if (remove.length)
  4529. _console.log('Removed parameters from link:', ...remove);
  4530. if (params.length)
  4531. parser.search = `?${params.join('&')}`;
  4532. else
  4533. parser.search = '';
  4534. t.href = parser.href;
  4535. }
  4536. }, false);
  4537. }
  4538. },
  4539.  
  4540. 'razlozhi.ru': {
  4541. now() {
  4542. nt.define('cadb', false);
  4543. for (let func of ['createShadowRoot', 'attachShadow'])
  4544. if (func in _Element)
  4545. _Element[func] = function () {
  4546. return this.cloneNode();
  4547. };
  4548. }
  4549. },
  4550.  
  4551. 'rbc.ru': {
  4552. other: 'autonews.ru, rbcplus.ru, sportrbc.ru',
  4553. now() {
  4554. scriptLander(() => selectiveCookies('adb_on'), selectiveCookies);
  4555. let _RA;
  4556. let setArgs = {
  4557. 'showBanners': true,
  4558. 'showAds': true,
  4559. 'banners.staticPath': '',
  4560. 'paywall.staticPath': '',
  4561. 'banners.dfp.config': [],
  4562. 'banners.dfp.pageTargeting': () => null,
  4563. };
  4564. Object.defineProperty(win, 'RA', {
  4565. get() {
  4566. return _RA;
  4567. },
  4568. set(vl) {
  4569. _console.log('RA =', vl);
  4570. if ('repo' in vl) {
  4571. _console.log('RA.repo =', vl.repo);
  4572. vl.repo = new Proxy(vl.repo, {
  4573. set(obj, name, val) {
  4574. if (name === 'banner') {
  4575. _console.log(`RA.repo.${name} =`, val);
  4576. val = new Proxy(val, {
  4577. get(obj, name) {
  4578. let res = obj[name];
  4579. if (typeof obj[name] === 'function') {
  4580. res = () => undefined;
  4581. if (name === 'getService')
  4582. res = service => {
  4583. if (service === 'dfp')
  4584. return {
  4585. getPlaces() {
  4586. return;
  4587. },
  4588. createPlaceholder() {
  4589. return;
  4590. }
  4591. };
  4592. return undefined;
  4593. };
  4594. res.toString = obj[name].toString.bind(obj[name]);
  4595. }
  4596. if (name === 'isInited')
  4597. res = true;
  4598. _console.trace(`get RA.repo.banner.${name}`, res);
  4599. return res;
  4600. }
  4601. });
  4602. }
  4603. obj[name] = val;
  4604. return true;
  4605. }
  4606. });
  4607. } else
  4608. _console.log('Unable to locate RA.repo');
  4609. _RA = new Proxy(vl, {
  4610. set(o, name, val) {
  4611. if (name === 'config') {
  4612. _console.log('RA.config =', val);
  4613. if ('set' in val) {
  4614. val.set = new Proxy(val.set, {
  4615. apply(set, that, args) {
  4616. let name = args[0];
  4617. if (name in setArgs)
  4618. args[1] = setArgs[name];
  4619. if (name in setArgs || name === 'checkad')
  4620. _console.log('RA.config.set(', ...args, ')');
  4621. return _apply(set, that, args);
  4622. }
  4623. });
  4624. val.set('showAds', true); // pretend ads already were shown
  4625. }
  4626. }
  4627. o[name] = val;
  4628. return true;
  4629. }
  4630. });
  4631. }
  4632. });
  4633. Object.defineProperty(win, 'bannersConfig', {
  4634. set() {},
  4635. get() {
  4636. return [];
  4637. }
  4638. });
  4639. // pretend there is a paywall landing on screen already
  4640. let pwl = _document.createElement('div');
  4641. pwl.style.display = 'none';
  4642. pwl.className = 'js-paywall-landing';
  4643. _document.documentElement.appendChild(pwl);
  4644. // detect and skip execution of one of the ABP detectors
  4645. win.setTimeout = new Proxy(win.setTimeout, {
  4646. apply(fun, that, args) {
  4647. if (typeof args[0] === 'function') {
  4648. let fts = _toString(args[0]);
  4649. if (/\.length\s*>\s*0\s*&&/.test(fts) && /:hidden/.test(fts)) {
  4650. _console.log('Skipped setTimout(', fts, args[1], ')');
  4651. return;
  4652. }
  4653. }
  4654. return _apply(fun, that, args);
  4655. }
  4656. });
  4657. // hide banner placeholders
  4658. createStyle('[data-banner-id], .banner__container, .banners__yandex__article { display: none !important }');
  4659. },
  4660. dom() {
  4661. // hide sticky banner place at the top of the page
  4662. for (let itm of _document.querySelectorAll('.l-sticky'))
  4663. if (itm.querySelector('.banner__container__link'))
  4664. itm.style.display = 'none';
  4665. }
  4666. },
  4667.  
  4668. 'reactor.cc': {
  4669. other: 'joyreactor.cc, pornreactor.cc',
  4670. now: () => scriptLander(() => {
  4671. selectiveEval();
  4672. win.open = function () {
  4673. throw new ReferenceError('Redirect prevention.');
  4674. };
  4675. nt.define('Worker', nt.func(nt.proxy({}, 'Worker'), 'Worker'));
  4676. let _CTRManager = win.CTRManager;
  4677. Object.defineProperty(win, 'CTRManager', {
  4678. get() {
  4679. return _CTRManager;
  4680. },
  4681. set(vl) {
  4682. if (vl === _CTRManager)
  4683. return true;
  4684. _CTRManager = {};
  4685. for (let name in vl)
  4686. if (typeof vl[name] !== 'function')
  4687. _CTRManager[name] = vl[name];
  4688. _CTRManager = nt.proxy(_CTRManager, 'CTRManager');
  4689. }
  4690. });
  4691. }, nullTools, selectiveEval),
  4692. click(e) {
  4693. let node = e.target;
  4694. if (node.nodeType === _Node.ELEMENT_NODE &&
  4695. node.style.position === 'absolute' &&
  4696. node.style.zIndex > 0)
  4697. node.parentNode.removeChild(node);
  4698. }
  4699. },
  4700.  
  4701. 'rp5.tld': {
  4702. now() {
  4703. Object.defineProperty(win, 'sContentBottom', {
  4704. set() {},
  4705. get() {
  4706. return '';
  4707. }
  4708. });
  4709. // skip timeout check for blocked requests
  4710. let _setTimeout = win.setTimeout;
  4711. win.setTimeout = function setTimeout(...args) {
  4712. let str = (typeof args[0] === 'string' ? args[0] : _toString(args[0]));
  4713. if (str.includes('xvb')) {
  4714. _console.log('Blocked setTimeout for:', str);
  4715. return;
  4716. }
  4717. return _setTimeout(...args);
  4718. };
  4719. },
  4720. dom() {
  4721. let node = selectNodeByTextContent('Разместить текстовое объявление', {
  4722. root: _de.querySelector('#content-wrapper'),
  4723. shallow: true
  4724. });
  4725. if (node)
  4726. node.style.display = 'none';
  4727. }
  4728. },
  4729.  
  4730. 'rsload.net': {
  4731. load() {
  4732. let dis = _document.querySelector('label[class*="cb-disable"]');
  4733. if (dis)
  4734. dis.click();
  4735. },
  4736. click(e) {
  4737. let t = e.target;
  4738. if (t && t.href && (/:\/\/\d+\.\d+\.\d+\.\d+\//.test(t.href)))
  4739. t.href = t.href.replace('://', '://rsload.net:rsload.net@');
  4740. }
  4741. },
  4742.  
  4743. 'rustorka.tld': {
  4744. other: [
  4745. 'rustorka.innal.top, rustorka2.innal.top, rustorka3.innal.top',
  4746. 'rustorka4.innal.top, rustorka5.innal.top, rustorka6.innal.top',
  4747. 'rustorka.naylo.top'
  4748. ].join(', '),
  4749. now: () => scriptLander(() => {
  4750. selectiveCookies('~default|(?!(PHPSESSID|__cfduid|announcements|bb_data|bb_t|id|opt_js|shout)$).*');
  4751. selectiveEval(/antiadblock/);
  4752. abortExecution.onGet('ads_script');
  4753. abortExecution.inlineScript('setTimeout', {
  4754. pattern: /("(\\x[0-9A-F]{2})+",\s?){4}/
  4755. });
  4756.  
  4757. const _doc_proto = ('cookie' in _Document) ? _Document : Object.getPrototypeOf(_document);
  4758. const _cookie = Object.getOwnPropertyDescriptor(_doc_proto, 'cookie');
  4759.  
  4760. if (_cookie && GM.info.scriptHandler) {
  4761. const asyncCookieCleaner = () => {
  4762. GM.cookie.list({
  4763. url: location.href
  4764. }).then(cookies => {
  4765. for (let cookie of (cookies || []))
  4766. if (cookie.name === cookie.value) {
  4767. GM.cookie.delete(cookie);
  4768. _console.log(`Removed cookie: ${cookie.name}=${cookie.value}`);
  4769. }
  4770. });
  4771. };
  4772. _cookie.get = new Proxy(_cookie.get, {
  4773. apply(fun, that, args) {
  4774. asyncCookieCleaner();
  4775. return _apply(fun, that, args);
  4776. }
  4777. });
  4778. _cookie.set = new Proxy(_cookie.set, {
  4779. apply(fun, that, args) {
  4780. _apply(fun, that, args);
  4781. asyncCookieCleaner();
  4782. return true;
  4783. }
  4784. });
  4785. Object.defineProperty(_doc_proto, 'cookie', _cookie);
  4786. }
  4787. }, selectiveCookies, abortExecution),
  4788. dom: () => _document.cookie.slice(0, 0)
  4789. },
  4790.  
  4791. 'rutracker.org': {
  4792. other: 'rutracker.lib, rutracker.net, rutracker.nl',
  4793. now: () => {
  4794. const ext = 'p-ext-link';
  4795. _Element.setAttribute = new Proxy(_Element.setAttribute, {
  4796. apply(fun, that, args) {
  4797. let [prop, classes] = args;
  4798. if (prop === 'class') {
  4799. let list = classes.split(/\s/);
  4800. if (list.includes(ext)) {
  4801. args[1] = list.filter(x => x !== ext).join(' ');
  4802. that.setAttribute('target', '_blank');
  4803. that.setAttribute('rel', 'noreferrer');
  4804. }
  4805. }
  4806. return _apply(fun, that, args);
  4807. }
  4808. });
  4809. }
  4810. },
  4811.  
  4812. 'rutube.ru': () => scriptLander(() => {
  4813. jsonFilter('creative', 'creative.id');
  4814. jsonFilter('interactives', 'interactives.0');
  4815. }, jsonFilter),
  4816.  
  4817. 'simpsonsua.tv': () => {
  4818. let _addEventListener = _Document.addEventListener;
  4819. _document.addEventListener = function (event, callback) {
  4820. if (event === 'DOMContentLoaded' && callback.toString().includes('show_warning'))
  4821. return;
  4822. return _addEventListener.apply(this, arguments);
  4823. };
  4824. nt.define('need_warning', 0);
  4825. nt.define('onYouTubeIframeAPIReady', nt.func(null, 'onYouTubeIframeAPIReady'));
  4826. },
  4827.  
  4828. 'smotret-anime-365.ru': () => scriptLander(() => {
  4829. deepWrapAPI(root => {
  4830. const _pause = _bindCall(root.Audio.prototype.pause);
  4831. const _addEventListener = _bindCall(root.Element.prototype.addEventListener);
  4832. let stopper = e => _pause(e.target);
  4833. root.Audio = new Proxy(root.Audio, {
  4834. construct(audio, args) {
  4835. let res = _construct(audio, args);
  4836. _addEventListener(res, 'play', stopper, true);
  4837. return res;
  4838. }
  4839. });
  4840. let _tagName_get = _bindCall(Object.getOwnPropertyDescriptor(_Element, 'tagName').get);
  4841. root.Document.prototype.createElement = new Proxy(root.Document.prototype.createElement, {
  4842. apply(fun, that, args) {
  4843. let res = _apply(fun, that, args);
  4844. if (_tagName_get(res) === 'AUDIO')
  4845. _addEventListener(res, 'play', stopper, true);
  4846. return res;
  4847. }
  4848. });
  4849. });
  4850. }, deepWrapAPI),
  4851.  
  4852. 'smotrim.ru': () => createStyle('.dialog-wrapper { display: none !important }'),
  4853.  
  4854. 'spaces.ru': () => {
  4855. gardener('div:not(.f-c_fll) > a[href*="spaces.ru/?Cl="]', /./, {
  4856. parent: 'div'
  4857. });
  4858. gardener('.js-banner_rotator', /./, {
  4859. parent: '.widgets-group'
  4860. });
  4861. },
  4862.  
  4863. 'spam-club.blogspot.co.uk': () => {
  4864. let _clientHeight = Object.getOwnPropertyDescriptor(_Element, 'clientHeight'),
  4865. _clientWidth = Object.getOwnPropertyDescriptor(_Element, 'clientWidth');
  4866. let wrapGetter = (getter) => {
  4867. let _getter = getter;
  4868. return function () {
  4869. let _size = _getter.apply(this, arguments);
  4870. return _size ? _size : 1;
  4871. };
  4872. };
  4873. _clientHeight.get = wrapGetter(_clientHeight.get);
  4874. _clientWidth.get = wrapGetter(_clientWidth.get);
  4875. Object.defineProperty(_Element, 'clientHeight', _clientHeight);
  4876. Object.defineProperty(_Element, 'clientWidth', _clientWidth);
  4877. let _onload = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onload'),
  4878. _set_onload = _onload.set;
  4879. _onload.set = function () {
  4880. if (this instanceof HTMLImageElement)
  4881. return true;
  4882. _set_onload.apply(this, arguments);
  4883. };
  4884. Object.defineProperty(HTMLElement.prototype, 'onload', _onload);
  4885. },
  4886.  
  4887. 'sport-express.ru': () => gardener('.js-relap__item', />Реклама\s+<\//, {
  4888. root: '.container',
  4889. observe: true
  4890. }),
  4891.  
  4892. 'sports.ru': {
  4893. other: 'tribuna.com',
  4894. now() {
  4895. // extra functionality: shows/hides panel at the top depending on scroll direction
  4896. createStyle({
  4897. '.user-panel__fixed': {
  4898. transition: 'top 0.2s ease-in-out!important'
  4899. },
  4900. '.popup__overlay.feedback': {
  4901. display: 'none!important'
  4902. },
  4903. '.user-panel-up': {
  4904. top: '-40px!important'
  4905. },
  4906. '#branding-layout': {
  4907. margin_top: '100px!important'
  4908. }
  4909. }, {
  4910. id: 'fixes',
  4911. protect: false
  4912. });
  4913. scriptLander(() => {
  4914. yandexRavenStub();
  4915. webpackJsonpFilter(/AdBlockDetector|addBranding|loadPlista/);
  4916. }, nullTools, yandexRavenStub, webpackJsonpFilter);
  4917. },
  4918. dom() {
  4919. (function lookForPanel() {
  4920. let panel = _document.querySelector('.user-panel__fixed');
  4921. if (!panel)
  4922. setTimeout(lookForPanel, 100);
  4923. else
  4924. window.addEventListener(
  4925. 'wheel',
  4926. function (e) {
  4927. if (e.deltaY > 0 && !panel.classList.contains('user-panel-up'))
  4928. panel.classList.add('user-panel-up');
  4929. else if (e.deltaY < 0 && panel.classList.contains('user-panel-up'))
  4930. panel.classList.remove('user-panel-up');
  4931. }, false
  4932. );
  4933. })();
  4934. }
  4935. },
  4936.  
  4937. 'stealthz.ru': {
  4938. dom() {
  4939. // skip timeout
  4940. let $ = _document.querySelector.bind(_document);
  4941. let [timer_1, timer_2] = [$('#timer_1'), $('#timer_2')];
  4942. if (!timer_1 || !timer_2)
  4943. return;
  4944. timer_1.style.display = 'none';
  4945. timer_2.style.display = 'block';
  4946. }
  4947. },
  4948.  
  4949. 'tortuga.wtf': () => {
  4950. nt.define('Object.prototype.hideab', undefined);
  4951. },
  4952.  
  4953. 'tv.animebest.org': {
  4954. now() {
  4955. let _eval = win.eval;
  4956. win.eval = new win.Proxy(win.eval, {
  4957. apply(evl, ths, args) {
  4958. if (typeof args[0] === 'string' &&
  4959. args[0].includes("'VASTP'")) {
  4960. args[0] = args[0].replace("'VASTP'", "''");
  4961. win.eval = _eval;
  4962. }
  4963. return Reflect.apply(evl, ths, args);
  4964. }
  4965. });
  4966. }
  4967. },
  4968.  
  4969. 'tv-kanali.online': () => {
  4970. win.setTimeout = new Proxy(win.setTimeout, {
  4971. apply(fun, that, args) {
  4972. if (args[0].name && args[0].name.includes('doAd'))
  4973. return;
  4974. if (args[1] === 30000) args[1] = 100;
  4975. return _apply(fun, that, args);
  4976. }
  4977. });
  4978. },
  4979.  
  4980. 'video.khl.ru': () => {
  4981. let props = new Set(['detectBlockers', 'detectBlockersByLink', 'detectBlockersByElement']);
  4982. win.Object.defineProperty = new Proxy(win.Object.defineProperty, {
  4983. apply(def, that, args) {
  4984. if (props.has(args[1])) {
  4985. args[2] = {
  4986. key: args[1],
  4987. value() {
  4988. _console.log(`Skipped ${args[1]} call.`);
  4989. }
  4990. };
  4991. _console.log(`Replaced method ${args[1]}.`);
  4992. }
  4993. return Reflect.apply(def, that, args);
  4994. }
  4995. });
  4996. },
  4997.  
  4998. 'xatab-repack.net': {
  4999. other: 'rg-mechanics.org',
  5000. now() {
  5001. abortExecution.onSet('blocked');
  5002. }
  5003. },
  5004.  
  5005. 'xittv.net': () => scriptLander(() => {
  5006. let logNames = ['setup', 'trigger', 'on', 'off', 'onReady', 'onError', 'getConfig', 'addPlugin', 'getAdBlock'];
  5007. let skipEvents = ['adComplete', 'adSkipped', 'adBlock', 'adRequest', 'adMeta', 'adImpression', 'adError', 'adTime', 'adStarted', 'adClick'];
  5008. let _jwplayer;
  5009. Object.defineProperty(win, 'jwplayer', {
  5010. get() {
  5011. return _jwplayer;
  5012. },
  5013. set(x) {
  5014. _jwplayer = new Proxy(x, {
  5015. apply(fun, that, args) {
  5016. let res = fun.apply(that, args);
  5017. res = new Proxy(res, {
  5018. get(obj, name) {
  5019. if (logNames.includes(name) && typeof obj[name] === 'function')
  5020. return new Proxy(obj[name], {
  5021. apply(fun, that, args) {
  5022. if (name === 'setup') {
  5023. let o = args[0];
  5024. if (o)
  5025. delete o.advertising;
  5026. }
  5027. if (name === 'on' || name === 'trigger') {
  5028. let events = typeof args[0] === 'string' ? args[0].split(" ") : null;
  5029. if (events.length === 1 && skipEvents.includes(events[0]))
  5030. return res;
  5031. if (events.length > 1) {
  5032. let names = [];
  5033. for (let event of events)
  5034. if (!skipEvents.includes(event))
  5035. names.push(event);
  5036. if (names.length > 0)
  5037. args[0] = names.join(" ");
  5038. else
  5039. return res;
  5040. }
  5041. }
  5042. let subres = fun.apply(that, args);
  5043. _console.trace(`jwplayer().${name}(`, ...args, `) >>`, res);
  5044. return subres;
  5045. }
  5046. });
  5047. return obj[name];
  5048. }
  5049. });
  5050. return res;
  5051. }
  5052. });
  5053. _console.log('jwplayer =', x);
  5054. }
  5055. });
  5056. }),
  5057.  
  5058. 'yandex.tld': {
  5059. other: 'yandexsport.tld',
  5060. now: () => {
  5061. // Generic Yandex Scripts
  5062. const mainScript = () => {
  5063. let nt = new nullTools({
  5064. log: false,
  5065. trace: true
  5066. });
  5067.  
  5068. let cookiefilter = '';
  5069. // ads on afisha.yandex.ru, however it looks like selectiveEval isn't perfect
  5070. // since eval could be called in scope to access properties of that scope and
  5071. // such calls with it active break functionality on metrika.yandex.ru
  5072. if (/(^|\.)afisha\./.test(location.hostname)) {
  5073. selectiveEval(/AdvManagerStatic/);
  5074. nt.define('Object.prototype._adbStyles', null);
  5075. nt.define('Object.prototype._adbClass', null);
  5076. cookiefilter += (cookiefilter.length ? '|' : '') + 'checkcookie';
  5077. }
  5078.  
  5079. selectiveCookies(cookiefilter);
  5080. // remove banner on the start page
  5081. let AwapsJsonAPI_Json = function (...args) {
  5082. _console.log('>> new AwapsJsonAPI.Json(', ...args, ')');
  5083. };
  5084. const cleaner = (_params, nodes) => {
  5085. try {
  5086. for (let i = 0; i < nodes.length; i++)
  5087. nodes[i].parentNode.parentNode.removeChild(nodes[i].parentNode);
  5088. _console.log(`Removed banner placeholder.`);
  5089. } catch (ignore) {
  5090. _console.log(`Can't locate placeholder to remove.`);
  5091. }
  5092. };
  5093. Object.assign(AwapsJsonAPI_Json.prototype, {
  5094. checkBannerVisibility: nt.func(true, 'AwapsJsonAPI.Json.checkBannerVisibility'),
  5095. autorefresh: nt.proxy(cleaner, 'AwapsJsonAPI.Json.prototype.autorefresh'),
  5096. addIframeContent: nt.proxy(cleaner, 'AwapsJsonAPI.Json.prototype.addIframeContent'),
  5097. getHTML: nt.func('', 'AwapsJsonAPI.Json.getHTML')
  5098. });
  5099. AwapsJsonAPI_Json.prototype = nt.proxy(AwapsJsonAPI_Json.prototype, 'AwapsJsonAPI.Json.prototype');
  5100. AwapsJsonAPI_Json = nt.proxy(AwapsJsonAPI_Json);
  5101. if ('AwapsJsonAPI' in win) {
  5102. _console.log('Oops! AwapsJsonAPI already defined.');
  5103. let f = win.AwapsJsonAPI.Json;
  5104. win.AwapsJsonAPI.Json = AwapsJsonAPI_Json;
  5105. if (f && f.prototype)
  5106. f.prototype = AwapsJsonAPI_Json.prototype;
  5107. } else
  5108. nt.define('AwapsJsonAPI', nt.proxy({
  5109. Json: AwapsJsonAPI_Json
  5110. }));
  5111.  
  5112. let parseExport = x => {
  5113. if (!x)
  5114. return x;
  5115. // remove banner placeholder
  5116. if (x.banner && x.banner.cls && x.banner.cls.banner__parent) {
  5117. let hide = pattern => {
  5118. for (let banner of _document.querySelectorAll(pattern)) {
  5119. _setAttribute(banner, 'style', 'display:none!important');
  5120. _console.log('Hid banner placeholder.');
  5121. }
  5122. };
  5123. let _parent = `.${x.banner.cls.banner__parent}`;
  5124. hide(_parent);
  5125. _document.addEventListener('DOMContentLoaded', () => hide(_parent), false);
  5126. }
  5127.  
  5128. // remove banner data and some other stuff
  5129. delete x.banner;
  5130. delete x.consistency;
  5131. delete x['i-bannerid'];
  5132. delete x['i-counter'];
  5133. delete x['promo-curtain'];
  5134.  
  5135. // remove parts of ga-counter (complete removal break "ТВ Онлайн")
  5136. if (x['ga-counter'] && x['ga-counter'].data) {
  5137. x['ga-counter'].data.id = 0;
  5138. delete x['ga-counter'].data.ether;
  5139. delete x['ga-counter'].data.iframeSrc;
  5140. delete x['ga-counter'].data.iframeSrcEx;
  5141. }
  5142.  
  5143. // remove adblock detector parameters and clean up detector cookie
  5144. if ('adb' in x) {
  5145. let cookie = x.adb.data ? x.adb.data.cookie : undefined;
  5146. if (cookie) {
  5147. selectiveCookies(cookie);
  5148. x.adb.data.adb = 0;
  5149. }
  5150. delete x.adb;
  5151. }
  5152.  
  5153. return x;
  5154. };
  5155. // Yandex banner on main page and some other things
  5156. let _home = win.home,
  5157. _home_set = !!_home;
  5158. Object.defineProperty(win, 'home', {
  5159. get() {
  5160. return _home;
  5161. },
  5162. set(vl) {
  5163. if (!_home_set && vl === _home)
  5164. return;
  5165. _home_set = false;
  5166. _console.log('home =', vl);
  5167. let _home_export = parseExport(vl.export);
  5168. Object.defineProperty(vl, 'export', {
  5169. get() {
  5170. return _home_export;
  5171. },
  5172. set(vl) {
  5173. _home_export = parseExport(vl);
  5174. }
  5175. });
  5176. _home = vl;
  5177. }
  5178. });
  5179.  
  5180. // adblock circumvention on some Yandex domains
  5181. yandexRavenStub();
  5182.  
  5183. // news, sport, docviewer in emails and probably other places
  5184. abortExecution.onGet('yaads.adRenderedCount');
  5185. let AdvertPartner = nt.func(false, 'AdvertPartner');
  5186. nt.defineOn(AdvertPartner, 'defaultProps', {}, 'AdvertPartner.');
  5187. nt.defineOn(AdvertPartner, 'contextTypes', [], 'AdvertPartner.');
  5188. nt.define('Object.prototype.AdvertPartner', AdvertPartner);
  5189. // ads in videoplayer
  5190. nt.define('Object.prototype.useAbdBundle', false);
  5191.  
  5192. (path => { // code specific for certain paths on yandex
  5193. const paths = {
  5194. news: () => {
  5195. createStyle(
  5196. 'div[class]:not(.mg-grid__col) > .mg-grid__row > .mg-grid__col:last-child,' +
  5197. '.news-top-rubric-heading > span:only-child, div[class*="_banger"] { display: none !important }'
  5198. );
  5199. gardener('.mg-grid__col > div[class*="_type_"]', /./, {
  5200. root: '.news-app__feed',
  5201. parent: '.mg-grid__col',
  5202. observe: true,
  5203. hide: true
  5204. });
  5205. },
  5206. sport: () => {
  5207. createStyle('.mg-page-layout-item div[class*="_type_"] { display: none !important }');
  5208. gardener(
  5209. '.mg-page-layout-item > .mg-page-layout-item__card > div[class*="_type_"], ' +
  5210. '.mg-page-layout-item > span > .mg-page-layout-item__card > div[class*="_type_"]',
  5211. /./, {
  5212. parent: '.mg-page-layout-item',
  5213. observer: true,
  5214. hide: true
  5215. }
  5216. );
  5217. },
  5218. pogoda: () => createStyle(
  5219. 'div[class^="content "][data-bem] > .content__bottom ~ div[class*="card "],' +
  5220. '[class*="segment__container"] > div > [class^="card "][class*="_"],' +
  5221. '.b-statcounter + div[class] > div[id][class] { display: none !important }'
  5222. )
  5223. };
  5224. if (paths[path]) paths[path]();
  5225. })(location.pathname.slice(1, (x => x < 0 ? undefined : x)(location.pathname.indexOf('/', 1))).toLowerCase());
  5226.  
  5227. // abp detector cookie on yandex pogoda and afisha
  5228. win.Element.prototype.getAttribute = new Proxy(win.Element.prototype.getAttribute, {
  5229. apply(get, el, args) {
  5230. let res = _apply(get, el, args);
  5231. if (res && res.length > 20 && el instanceof HTMLBodyElement)
  5232. try {
  5233. let o = JSON.parse(res),
  5234. found = false,
  5235. check;
  5236. for (let prop in o) {
  5237. check = 'param' in o[prop] || 'aabCookieName' in o[prop];
  5238. if (check || 'banners' in o[prop]) {
  5239. found = true;
  5240. if (check)
  5241. selectiveCookies(o[prop].param || o[prop].aabCookieName);
  5242. _console.log(el.tagName, o, 'removed', o[prop]);
  5243. delete o[prop];
  5244. }
  5245. }
  5246. if (!found) _console.log(el.tagName, o);
  5247. res = JSON.stringify(o);
  5248. } catch (ignore) {}
  5249. return res;
  5250. }
  5251. });
  5252. };
  5253. scriptLander(mainScript, nullTools, yandexRavenStub, abortExecution, selectiveCookies, selectiveEval);
  5254.  
  5255. if ('attachShadow' in _Element) try {
  5256. let fakeRoot = () => ({
  5257. firstChild: null,
  5258. appendChild() {
  5259. return null;
  5260. },
  5261. querySelector() {
  5262. return null;
  5263. },
  5264. querySelectorAll() {
  5265. return null;
  5266. }
  5267. });
  5268. _Element.createShadowRoot = fakeRoot;
  5269. let shadows = new WeakMap();
  5270. let _attachShadow = Object.getOwnPropertyDescriptor(_Element, 'attachShadow');
  5271. _attachShadow.value = function () {
  5272. return shadows.set(this, fakeRoot()).get(this);
  5273. };
  5274. Object.defineProperty(_Element, 'attachShadow', _attachShadow);
  5275. let _shadowRoot = Object.getOwnPropertyDescriptor(_Element, 'shadowRoot');
  5276. _shadowRoot.set = () => null;
  5277. _shadowRoot.get = function () {
  5278. return shadows.has(this) ? shadows.get(this) : undefined;
  5279. };
  5280. Object.defineProperty(_Element, 'shadowRoot', _shadowRoot);
  5281. } catch (e) {
  5282. _console.warn('Unable to wrap Element.prototype.attachShadow\n', e);
  5283. }
  5284.  
  5285. // Disable banner styleSheet (on main page)
  5286. document.addEventListener('DOMContentLoaded', () => {
  5287. for (let sheet of document.styleSheets)
  5288. try {
  5289. for (let rule of sheet.cssRules)
  5290. if (rule.cssText.includes(' 728px 90px')) {
  5291. rule.parentStyleSheet.disabled = true;
  5292. _console.log('Disabled banner styleSheet:', rule.parentStyleSheet);
  5293. }
  5294. } catch (ignore) {}
  5295. }, false);
  5296.  
  5297. // Subdomain-specific Yandex scripts
  5298. const subDomain = location.hostname.slice(0, location.hostname.indexOf('.'));
  5299.  
  5300. // Yandex Mail ads
  5301. if (subDomain === 'mail') {
  5302. let wrap = vl => {
  5303. if (!vl)
  5304. return vl;
  5305. _console.log('Daria =', vl);
  5306. nt.defineOn(vl, 'AdBlock', nt.proxy({
  5307. detect: nt.func(new Promise(() => null), 'Daria.AdBlock.detect'),
  5308. enabled: false
  5309. }), 'Daria.');
  5310. nt.defineOn(vl, 'AdvPresenter', nt.proxy({
  5311. _config: nt.proxy({
  5312. banner: false,
  5313. done: false,
  5314. line: false
  5315. })
  5316. }), 'Daria.');
  5317. if (vl.Config) {
  5318. delete vl.Config.adBlockDetector;
  5319. delete vl.Config['adv-url'];
  5320. delete vl.Config.cryprox;
  5321. if (vl.Config.features) {
  5322. delete vl.Config.features.web_adloader_with_cookie_cache;
  5323. delete vl.Config.features.web_ads;
  5324. delete vl.Config.features.web_ads_mute;
  5325. }
  5326. vl.Config.mayHaveAdv = false;
  5327. }
  5328. return vl;
  5329. };
  5330. let _Daria = wrap(win.Daria);
  5331. if (_Daria)
  5332. _console.log('Wrapped already existing object "Daria".');
  5333. Object.defineProperty(win, 'Daria', {
  5334. get() {
  5335. return _Daria;
  5336. },
  5337. set(vl) {
  5338. if (vl === _Daria)
  5339. return;
  5340. _Daria = wrap(vl);
  5341. }
  5342. });
  5343. // Buttons to pay to disable ads
  5344. createStyle('.ns-view-mail-pro-left-column-button, .PSHeader-Pro { display: none !important }');
  5345. }
  5346.  
  5347. // Detector and ads on Yandex Music
  5348. if (subDomain === 'music') {
  5349. nt.define('tryPay', nt.func(null, 'tryPay'));
  5350. nt.define('Object.prototype.initMegabannerAPI', nt.func(null, 'initMegabannerAPI'));
  5351. nt.define('Object.prototype.mediaAd', undefined);
  5352. nt.define('Object.prototype.detect', () => new Promise(() => null));
  5353. nt.define('Object.prototype.loadContext', () => new Promise(r => r()));
  5354. nt.define('Object.prototype.antiAdbSetup', nt.func(null, 'ya.music.antiAdbSetup'));
  5355. }
  5356.  
  5357. const isSearch = /^\/(yand)?search[/?]/i.test(location.pathname);
  5358. if (['mail', 'music', 'tv', 'yandexsport'].includes(subDomain) || isSearch) {
  5359. // prevent/defuse adblock detector and cleanup localStorage
  5360. for (let name in localStorage)
  5361. if (name.startsWith('videoplayer-ad-session-') || ['ic', 'yu', 'ludca', 'test'].includes(name))
  5362. localStorage.removeItem(name);
  5363.  
  5364. const mapsmb = Symbol('lsOverrideMap');
  5365. let lsOverride = {
  5366. // generic
  5367. '_mt__data': '',
  5368. 'yandexJSPlayerApiSavedSingleVideoSessionWatchedTimeSinceAd': Math.floor(Math.random() * 1000000) / 1000,
  5369. 'yandexJSPlayerApiSavedSingleVideoSessionWatchedTimeSinceAdUtcTimestamp': true,
  5370. // Yandex Music specific
  5371. 'playerBrandingType': null,
  5372. 'paywall-onloaded': true,
  5373. 'gdpr-welcome': true
  5374. };
  5375. lsOverride[mapsmb] = new Map();
  5376. lsOverride = new Proxy(lsOverride, {
  5377. get(that, name) {
  5378. if (name === mapsmb)
  5379. return that[name];
  5380. if (name === 'yandexJSPlayerApiSavedSingleVideoSessionWatchedTimeSinceAdUtcTimestamp')
  5381. return String((new Date()).getTime() / 1000 - that.yandexJSPlayerApiSavedSingleVideoSessionWatchedTimeSinceAd).slice(1, 14);
  5382. if (name === 'paywall-onloaded' || name === 'gdpr-welcome') {
  5383. let val = that[mapsmb].get(name);
  5384. if (!val) return val;
  5385. let obj = JSON.parse(val);
  5386. let dt = Math.floor((new Date()).getTime() + Math.random() * 3 * 86400000 + 2 * 86400000);
  5387. for (let itm in obj)
  5388. obj[itm] = dt;
  5389. return JSON.stringify(obj);
  5390. }
  5391. return String(that[name]);
  5392. },
  5393. set(that, name, val) {
  5394. that[mapsmb].set(name, val);
  5395. return true;
  5396. }
  5397. });
  5398. const _getItem = win.localStorage.getItem;
  5399. const _localStorage = new Proxy(win.localStorage, {
  5400. get(that, name) {
  5401. if (name === 'getItem') {
  5402. return (it) => {
  5403. //console.log('get', it, _getItem.call(that, it));
  5404. if (it in lsOverride) {
  5405. lsOverride[it] = _getItem.call(that, it);
  5406. //console.log('override', lsOverride[it]);
  5407. return lsOverride[it];
  5408. }
  5409. return _getItem.call(that, it);
  5410. };
  5411. }
  5412. if (name === 'removeItem' || name === 'setItem')
  5413. return that[name].bind(that);
  5414. if (name in lsOverride) {
  5415. lsOverride[name] = _localStorage[name];
  5416. _localStorage[name] = lsOverride[name];
  5417. return lsOverride[name];
  5418. }
  5419. return that[name];
  5420. }
  5421. });
  5422. Object.defineProperty(win, 'localStorage', {
  5423. enumerable: true,
  5424. configurable: true,
  5425. get: new Proxy(function localStorage() {
  5426. return _localStorage;
  5427. }, {})
  5428. });
  5429.  
  5430. // cookie cleaner
  5431. let yp_keepCookieParts = /\.(sp|ygo|ygu|fblkv2)\./;
  5432. // ygo = city id; ygu = detect city automatically; fblkv2 = visible sections on the main page under search
  5433. let _doc_proto = ('cookie' in _Document) ? _Document : Object.getPrototypeOf(_document);
  5434. let _cookie = Object.getOwnPropertyDescriptor(_doc_proto, 'cookie');
  5435. if (_cookie) {
  5436. let _set_cookie = _bindCall(_cookie.set);
  5437. _cookie.set = function (value) {
  5438. if (/^(mda=|yp=|ys=|yabs-|__|bltsr=)/.test(value))
  5439. // remove value, set expired
  5440. if (!value.startsWith('yp=')) {
  5441. value = value.replace(/^([^=]+=)[^;]+/, '$1').replace(/(expires=)[\w\s\d,]+/, '$1Thu, 01 Jan 1970 00');
  5442. _console.trace('expire cookie', value.match(/^[^=]+/)[0]);
  5443. } else {
  5444. let parts = value.split(';');
  5445. let values = parts[0].split('#').filter(part => yp_keepCookieParts.test(part));
  5446. if (values.length)
  5447. values[0] = values[0].replace(/^yp=/, '');
  5448. let res = `yp=${values.join('#')}`;
  5449. _console.trace(`set cookie ${res}, dropped ${parts[0].replace(res,'')}`);
  5450. parts[0] = res;
  5451. value = parts.join(';');
  5452. }
  5453. return _set_cookie(this, value);
  5454. };
  5455. Object.defineProperty(_doc_proto, 'cookie', _cookie);
  5456. }
  5457. }
  5458. },
  5459. dom: () => {
  5460. { // Partially based on https://greasyfork.org/en/scripts/22737-remove-yandex-redirect
  5461. let count = 0,
  5462. lock = false;
  5463. const log = () => {
  5464. count++;
  5465. if (lock)
  5466. return;
  5467. setTimeout(() => {
  5468. _console.log('Removed tracking attributes from', count, 'links.');
  5469. count = 0;
  5470. lock = false;
  5471. }, 3333);
  5472. lock = true;
  5473. };
  5474. const selectors = (
  5475. 'A[onmousedown*="/jsredir"],' +
  5476. 'A[data-log-node],' +
  5477. 'A[data-vdir-href],' +
  5478. 'A[data-counter]'
  5479. );
  5480. const removeTrackingAttributes = (link) => {
  5481. _removeAttribute(link, 'onmousedown');
  5482. _removeAttribute(link, 'data-log-node');
  5483. // data-vdir-href
  5484. _removeAttribute(link, 'data-vdir-href');
  5485. _removeAttribute(link, 'data-orig-href');
  5486. // data-counter
  5487. _removeAttribute(link, 'data-counter');
  5488. _removeAttribute(link, 'data-bem');
  5489. log();
  5490. };
  5491. const removeTracking = (scope) => {
  5492. if (scope instanceof Element)
  5493. for (let link of scope.querySelectorAll(selectors))
  5494. removeTrackingAttributes(link);
  5495. };
  5496.  
  5497. removeTracking(_document);
  5498. (new MutationObserver(
  5499. function (ms) {
  5500. let m, node;
  5501. for (m of ms)
  5502. for (node of m.addedNodes)
  5503. if (node instanceof HTMLAnchorElement && node.matches(selectors))
  5504. removeTrackingAttributes(node);
  5505. else
  5506. removeTracking(node);
  5507. }
  5508. )).observe(_de, {
  5509. childList: true,
  5510. subtree: true
  5511. });
  5512. }
  5513.  
  5514. // Subdomain-specific Yandex scripts
  5515. const subDomain = location.hostname.slice(0, location.hostname.indexOf('.'));
  5516.  
  5517. // Function to attach an observer to monitor dynamic changes on the page
  5518. const pageUpdateObserver = (func, obj, params) => {
  5519. if (obj)
  5520. (new MutationObserver(func))
  5521. .observe(obj, (params || {
  5522. childList: true,
  5523. subtree: true
  5524. }));
  5525. };
  5526. // Short name for parentNode.removeChild
  5527. const remove = node => {
  5528. if (!node || !node.parentNode)
  5529. return false;
  5530. _console.log('Removed node.');
  5531. node.parentNode.removeChild(node);
  5532. };
  5533. // Short name for setAttribute style to display:none
  5534. const hide = node => {
  5535. if (!node)
  5536. return false;
  5537. _console.log('Hid node.');
  5538. _setAttribute(node, 'style', 'display:none!important');
  5539. };
  5540.  
  5541. if (subDomain === 'music') {
  5542. const removeMusicAds = () => {
  5543. for (let node of _querySelectorAll('.ads-block'))
  5544. remove(node);
  5545. };
  5546. pageUpdateObserver(removeMusicAds, _querySelector('.sidebar'));
  5547. removeMusicAds();
  5548. }
  5549.  
  5550. if (subDomain === 'tv') {
  5551. const removeTVAds = () => {
  5552. const yadWord = /Яндекс.Директ/i;
  5553. for (let node of _querySelectorAll('div[class^="_"][data-reactid] > div'))
  5554. if (yadWord.test(node.textContent) || node.querySelector('iframe:not([src])')) {
  5555. if (node.offsetWidth) {
  5556. let pad = _document.createElement('div');
  5557. _setAttribute(pad, 'style', `width:${node.offsetWidth}px`);
  5558. node.parentNode.appendChild(pad);
  5559. }
  5560. remove(node);
  5561. }
  5562. };
  5563. pageUpdateObserver(removeTVAds, _document.body);
  5564. removeTVAds();
  5565. }
  5566.  
  5567. const isSearch = /^\/(yand)?search[/?]/i.test(location.pathname);
  5568. if (isSearch) {
  5569. const removeSearchAds = () => {
  5570. const adWords = /Реклама|Ad/i;
  5571. for (let node of _querySelectorAll('.serp-item'))
  5572. if (_getAttribute(node, 'role') === 'complementary' ||
  5573. adWords.test((node.querySelector('.label') || {}).textContent))
  5574. hide(node);
  5575. };
  5576. pageUpdateObserver(removeSearchAds, _querySelector('.main__content'));
  5577. removeSearchAds();
  5578. }
  5579.  
  5580. if (['mail', 'music', 'tv', 'yandexsport'].includes(subDomain) || isSearch) {
  5581. // Generic ads removal and fixes
  5582. for (let node of _querySelectorAll('.serp-header'))
  5583. node.style.marginTop = '0';
  5584. for (let node of _querySelectorAll(
  5585. '.serp-adv__head + .serp-item,' +
  5586. '#adbanner,' +
  5587. '.serp-adv,' +
  5588. '.b-spec-adv,' +
  5589. 'div[class*="serp-adv__"]:not(.serp-adv__found):not(.serp-adv__displayed)'
  5590. )) remove(node);
  5591. }
  5592. }
  5593. },
  5594.  
  5595. 'yap.ru': {
  5596. other: 'yaplakal.com',
  5597. now() {
  5598. gardener('form > table[id^="p_row_"]:nth-of-type(2)', /member1438|Administration/);
  5599. gardener('.icon-comments', /member1438|Administration|\/go\/\?http/, {
  5600. parent: 'tr',
  5601. siblings: -2
  5602. });
  5603. }
  5604. },
  5605.  
  5606. 'yapx.ru': () => scriptLander(() => {
  5607. selectiveCookies('adblock_state|adblock_views');
  5608. nt.define('blockAdBlock', {
  5609. on: nt.func(nt.proxy({}, 'blockAdBlock.on', nt.NULL), 'blockAdBlock.on'),
  5610. check: nt.func(null, 'blockAdBlock.check')
  5611. });
  5612. }, selectiveCookies, nullTools),
  5613.  
  5614. 'youtube.com': () => scriptLander(() => {
  5615. jsonFilter('playerResponse.adPlacements playerResponse.playerAds adPlacements playerAds');
  5616. }, jsonFilter),
  5617.  
  5618. 'znanija.com': () => scriptLander(() => {
  5619. localStorage.clear();
  5620. }, abortExecution)
  5621. };
  5622.  
  5623. // replace '.tld' in domain names, add alternative domain names if present and wrap functions into objects
  5624. {
  5625. const parts = _document.domain.split('.');
  5626. const tld = /\.tld$/;
  5627. const tldSubstitur = (() => {
  5628. // stores TLD of current domain (simplistic TLD implementation)
  5629. const last = parts.length - 1;
  5630. const tld = ['', parts[last]];
  5631. const secondLevel = [
  5632. 'biz', 'com', 'edu', 'gov', 'info', 'int', 'mil', 'net', 'org', 'pro'
  5633. ];
  5634. // add second from the end part of domain name as part of the TLD substitutor
  5635. // when domain name consists of more than 2 parts and it looks like a part of TLD
  5636. if ((parts[0] !== 'www' && parts.length > 2 || parts.length > 3) &&
  5637. (parts[last - 1].length < 3 || secondLevel.includes(parts[last - 1])))
  5638. tld.splice(0, 1, parts[last - 1]);
  5639. return tld.join('.');
  5640. })();
  5641. for (let name in scripts) {
  5642. if (typeof scripts[name] === 'function')
  5643. scripts[name] = {
  5644. now: scripts[name]
  5645. };
  5646. if (name.endsWith('.tld'))
  5647. scripts[name.replace(tld, tldSubstitur)] = scripts[name];
  5648. for (let domain of (scripts[name].other && scripts[name].other.split(/,\s*/) || [])) {
  5649. domain = domain.replace(tld, tldSubstitur);
  5650. if (domain in scripts)
  5651. _console.log('Error in scripts list. Script for', name, 'replaced script for', domain);
  5652. scripts[domain] = scripts[name];
  5653. }
  5654. delete scripts[name].other;
  5655. }
  5656. // scripts lookup
  5657. const windowEvents = ['load', 'unload', 'beforeunload'];
  5658. let domain;
  5659. while (parts.length > 1) {
  5660. domain = parts.join('.');
  5661. if (domain in scripts) {
  5662. for (let when in scripts[domain]) {
  5663. let script = scripts[domain][when];
  5664. if (when === 'now')
  5665. script();
  5666. else if (when === 'dom')
  5667. _document.addEventListener('DOMContentLoaded', script);
  5668. else if (windowEvents.includes(when))
  5669. win.addEventListener(when, scripts[domain][when]);
  5670. else
  5671. _document.addEventListener(when, scripts[domain][when]);
  5672. }
  5673. }
  5674. parts.shift();
  5675. }
  5676. }
  5677.  
  5678. // Batch script lander
  5679. if (!skipLander)
  5680. landScript(batchLand, batchPrepend);
  5681.  
  5682. { // JS Fixes Tools Menu
  5683. const incompatibleScriptHandler = !/^(Tamper|Violent)monkey$/.test(GM.info.scriptHandler) || GM.info.scriptHandler === 'Violentmonkey' && isFirefox;
  5684. // Debug function, lists all unusual window properties
  5685. const isNativeFunction = /^[^{]*\{[\s\r\n]*\[native\scode\][\s\r\n]*\}$/;
  5686. const getStrangeObjectsList = () => {
  5687. _console.group('Window strangers list');
  5688. const _skip = 'frames/self/window/webkitStorageInfo'.split('/');
  5689. for (let n of Object.getOwnPropertyNames(win))
  5690. try {
  5691. let val = win[n];
  5692. if (val && !_skip.includes(n) && (win !== window && val !== window[n] || win === window) &&
  5693. (typeof val !== 'function' || typeof val === 'function' && !isNativeFunction.test(_toString(val))))
  5694. _console.log(`${n} =`, val);
  5695. } catch (e) {
  5696. _console.log(n, 'returns error on read', e);
  5697. }
  5698. _console.groupEnd('Window strangers list');
  5699. };
  5700.  
  5701. const lines = {
  5702. linked: [],
  5703. MenuOptions: {
  5704. eng: 'Options',
  5705. rus: 'Настройки'
  5706. },
  5707. MenuCompatibilityWarning: {
  5708. eng: 'is not supported',
  5709. rus: 'не поддерживается'
  5710. },
  5711. langs: {
  5712. eng: 'English',
  5713. rus: 'Русский'
  5714. },
  5715. sObjBtn: {
  5716. eng: 'List unusual "window" properties in console',
  5717. rus: 'Вывести в консоль нестандартные свойства «window»'
  5718. },
  5719. HeaderTools: {
  5720. eng: 'Tools',
  5721. rus: 'Инструменты'
  5722. },
  5723. HeaderOptions: {
  5724. eng: 'Options',
  5725. rus: 'Настройки'
  5726. },
  5727. AccessStatisticsLabel: {
  5728. eng: 'Display stubs access statistics and JSON filter',
  5729. rus: 'Выводить статистику запросов к заглушкам и JSON фильтра'
  5730. },
  5731. AbortExecutionStatisticsLabel: {
  5732. eng: 'Display abort execution statistics',
  5733. rus: 'Выводить статистику прерывания исполнения скриптов'
  5734. },
  5735. LogAttachedCSSLabel: {
  5736. eng: 'Log CSS attached to a page',
  5737. rus: 'Журналировать CSS добавленные на страницу'
  5738. },
  5739. BlockNotificationPermissionRequestsLabel: {
  5740. eng: 'Block requests to Show Notifications on sites',
  5741. rus: 'Блокировать запросы Показывать Уведомления на сайтах'
  5742. },
  5743. ShowScriptHandlerCompatibilityWarningLabel: {
  5744. eng: 'Show compatibility warning in menu next to Options',
  5745. rus: 'Отображать предупреждение о совместимости в меню рядом с Настройками'
  5746. },
  5747. reg(el, name) {
  5748. this[name].link = el;
  5749. this.linked.push(name);
  5750. },
  5751. setLang(lang = 'eng') {
  5752. for (let name of this.linked) {
  5753. const el = this[name].link;
  5754. const label = this[name][lang];
  5755. el.textContent = label;
  5756. }
  5757. this.langs.link.value = lang;
  5758. jsf.Lang = lang;
  5759. }
  5760. };
  5761.  
  5762. const _createTextNode = _Document.createTextNode.bind(_document);
  5763. const createOptionsWindow = () => {
  5764. const root = _createElement('div'),
  5765. shadow = _attachShadow ? _attachShadow(root, {
  5766. mode: 'closed'
  5767. }) : root,
  5768. overlay = _createElement('div'),
  5769. inner = _createElement('div');
  5770.  
  5771. overlay.id = 'overlay';
  5772. overlay.appendChild(inner);
  5773. shadow.appendChild(overlay);
  5774.  
  5775. inner.id = 'inner';
  5776. inner.br = function appendBreakLine() {
  5777. return this.appendChild(_createElement('br'));
  5778. };
  5779.  
  5780. createStyle({
  5781. 'h2': {
  5782. margin_top: 0
  5783. },
  5784. 'h2, h3': {
  5785. margin_block_end: '0.5em'
  5786. },
  5787. 'div, button, select, input': {
  5788. font_family: 'Helvetica, Arial, sans-serif',
  5789. font_size: '12pt'
  5790. },
  5791. 'button': {
  5792. background: 'linear-gradient(to bottom, #f0f0f0 5%, #c0c0c0 100%)',
  5793. border_radius: '3px',
  5794. border: '1px solid #a1a1a1',
  5795. color: '#000000',
  5796. text_shadow: '0px 1px 0px #d4d4d4'
  5797. },
  5798. 'button:hover': {
  5799. background: 'linear-gradient(to bottom, #c0c0c0 5%, #f0f0f0 100%)'
  5800. },
  5801. 'button:active': {
  5802. position: 'relative',
  5803. top: '1px'
  5804. },
  5805. 'select': {
  5806. border: '1px solid darkgrey',
  5807. border_radius: '0px 0px 5px 5px',
  5808. border_top: '0px'
  5809. },
  5810. 'button:focus, select:focus': {
  5811. outline: 'none'
  5812. },
  5813. '#overlay': {
  5814. position: 'fixed',
  5815. top: 0,
  5816. left: 0,
  5817. bottom: 0,
  5818. right: 0,
  5819. background: 'rgba(0,0,0,0.65)',
  5820. z_index: 2147483647 // Highest z-index: Math.pow(2, 31) - 1
  5821. },
  5822. '#inner': {
  5823. background: 'whitesmoke',
  5824. color: 'black',
  5825. padding: '1.5em 1em 1.5em 1em',
  5826. max_width: '150ch',
  5827. position: 'absolute',
  5828. top: '50%',
  5829. left: '50%',
  5830. transform: 'translate(-50%, -50%)',
  5831. border: '1px solid darkgrey',
  5832. border_radius: '5px'
  5833. },
  5834. '#closeOptionsButton': {
  5835. float: 'right',
  5836. transform: 'translate(1em, -1.5em)',
  5837. border: 0,
  5838. border_radius: 0,
  5839. background: 'none',
  5840. box_shadow: 'none'
  5841. },
  5842. '#selectLang': {
  5843. float: 'right',
  5844. transform: 'translate(0, -1.5em)'
  5845. },
  5846. '.optionsLabel': {
  5847. padding_left: '1.5em',
  5848. text_indent: '-1em',
  5849. display: 'block'
  5850. },
  5851. '.optionsCheckbox': {
  5852. left: '-0.25em',
  5853. width: '1em',
  5854. height: '1em',
  5855. padding: 0,
  5856. margin: 0,
  5857. position: 'relative',
  5858. vertical_align: 'middle'
  5859. },
  5860. '@media (prefers-color-scheme: dark)': {
  5861. '#inner': {
  5862. background_color: '#292a2d',
  5863. color: 'white',
  5864. border: '1px solid #1a1b1e'
  5865. },
  5866. 'input': {
  5867. filter: 'invert(100%)'
  5868. },
  5869. 'button': {
  5870. background: 'linear-gradient(to bottom, #575757 5%, #303030 100%)',
  5871. border_color: '#575757',
  5872. color: '#f0f0f0',
  5873. text_shadow: '0px 1px 0px #171717'
  5874. },
  5875. 'button:hover': {
  5876. background: 'linear-gradient(to bottom, #303030 5%, #575757 100%)'
  5877. },
  5878. 'select': {
  5879. background_color: '#303030',
  5880. color: '#f0f0f0',
  5881. border: '1px solid #1a1b1e',
  5882. border_radius: '0px 0px 5px 5px',
  5883. border_top: '0px'
  5884. },
  5885. '#overlay': {
  5886. background: 'rgba(0,0,0,.85)',
  5887. }
  5888. }
  5889. }, {
  5890. root: shadow,
  5891. protect: false
  5892. });
  5893.  
  5894. // components
  5895. function createCheckbox(name) {
  5896. const checkbox = _createElement('input'),
  5897. label = _createElement('label');
  5898. checkbox.type = 'checkbox';
  5899. checkbox.classList.add('optionsCheckbox');
  5900. checkbox.checked = jsf[name];
  5901. checkbox.onclick = e => {
  5902. jsf[name] = e.target.checked;
  5903. return true;
  5904. };
  5905. label.classList.add('optionsLabel');
  5906. label.appendChild(checkbox);
  5907. const text = _createTextNode('');
  5908. label.appendChild(text);
  5909. Object.defineProperty(label, 'textContent', {
  5910. set(title) {
  5911. text.textContent = title;
  5912. }
  5913. });
  5914. return label;
  5915. }
  5916.  
  5917. // language & close
  5918. const closeBtn = _createElement('button');
  5919. closeBtn.onclick = () => _removeChild(root);
  5920. closeBtn.textContent = '\u2715';
  5921. closeBtn.id = 'closeOptionsButton';
  5922. inner.appendChild(closeBtn);
  5923.  
  5924. overlay.addEventListener('click', e => {
  5925. if (e.target === overlay) {
  5926. _removeChild(root);
  5927. e.preventDefault();
  5928. }
  5929. e.stopPropagation();
  5930. }, false);
  5931.  
  5932. const selectLang = _createElement('select');
  5933. for (let name in lines.langs) {
  5934. const langOption = _createElement('option');
  5935. langOption.value = name;
  5936. langOption.innerText = lines.langs[name];
  5937. selectLang.appendChild(langOption);
  5938. }
  5939. selectLang.id = 'selectLang';
  5940. lines.langs.link = selectLang;
  5941. inner.appendChild(selectLang);
  5942.  
  5943. selectLang.onchange = e => {
  5944. const lang = e.target.value;
  5945. lines.setLang(lang);
  5946. };
  5947.  
  5948. // fill options form
  5949. const header = _createElement('h2');
  5950. header.textContent = 'RU AdList JS Fixes';
  5951. inner.appendChild(header);
  5952.  
  5953. lines.reg(inner.appendChild(_createElement('h3')), 'HeaderTools');
  5954.  
  5955. const sObjBtn = _createElement('button');
  5956. sObjBtn.onclick = getStrangeObjectsList;
  5957. sObjBtn.textContent = '';
  5958. lines.reg(inner.appendChild(sObjBtn), 'sObjBtn');
  5959.  
  5960. lines.reg(inner.appendChild(_createElement('h3')), 'HeaderOptions');
  5961.  
  5962. lines.reg(inner.appendChild(createCheckbox('AccessStatistics')), 'AccessStatisticsLabel');
  5963. lines.reg(inner.appendChild(createCheckbox('AbortExecutionStatistics')), 'AbortExecutionStatisticsLabel');
  5964. lines.reg(inner.appendChild(createCheckbox('LogAttachedCSS')), 'LogAttachedCSSLabel');
  5965.  
  5966. inner.appendChild(_createElement('br'));
  5967. lines.reg(inner.appendChild(createCheckbox('BlockNotificationPermissionRequests')), 'BlockNotificationPermissionRequestsLabel');
  5968.  
  5969. if (incompatibleScriptHandler) {
  5970. inner.appendChild(_createElement('br'));
  5971. lines.reg(inner.appendChild(createCheckbox('ShowScriptHandlerCompatibilityWarning')), 'ShowScriptHandlerCompatibilityWarningLabel');
  5972. }
  5973.  
  5974. lines.setLang(jsf.Lang);
  5975.  
  5976. return root;
  5977. };
  5978.  
  5979. let optionsWindow;
  5980. GM_registerMenuCommand(lines.MenuOptions[jsf.Lang], () => _appendChild(optionsWindow = optionsWindow || createOptionsWindow()));
  5981. // add warning to script menu for non-Tampermonkey users
  5982. if (jsf.ShowScriptHandlerCompatibilityWarning && incompatibleScriptHandler)
  5983. GM_registerMenuCommand(`${GM.info.scriptHandler} ${lines.MenuCompatibilityWarning[jsf.Lang]}`, () => {
  5984. win.open(`https://greasyfork.org/${jsf.Lang.slice(0,2)}/scripts/19993-ru-adlist-js-fixes#additional-info`);
  5985. });
  5986. }
  5987. })();