RU AdList JS Fixes

try to take over the world!

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

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