RU AdList JS Fixes

try to take over the world!

目前为 2020-11-19 提交的版本,查看 最新版本

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