RU AdList JS Fixes

try to take over the world!

当前为 2021-06-18 提交的版本,查看 最新版本

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