RU AdList JS Fixes

try to take over the world!

目前為 2020-11-25 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name RU AdList JS Fixes
  3. // @namespace ruadlist_js_fixes
  4. // @version 20201125.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. 'meteo.ua': () => zmcPlug('n11191753'),
  2559. 'nv.ua': () => zmcPlug('n10300948'),
  2560. 'ostro.org': () => zmcPlug('n10101319'),
  2561. 'pravda.com.ua': () => {
  2562. zmcPlug('n09221555');
  2563. nt.define('AdnetLoadScript');
  2564. },
  2565. 'real-vin.com': () => zmcPlug('n09201149'),
  2566. // custom zmc-related fixes
  2567. 'kzblow.info': () => documentRewrite(/<script>\(function\(\w\w,.*?['"]n\d+['"]\);<\/script>/, '<!-- removed -->'),
  2568. // disables ads when specific cookies are set
  2569. 'liga.net': () => (_document.cookie = 'isShowAd=false; domain=.liga.net', _document.cookie = 'is_login=true; domain=.liga.net'),
  2570. // disables ads if screen width is below 1200
  2571. 'segodnya.ua': () => {
  2572. nt.define('document.documentElement', new Proxy(_document.documentElement, {
  2573. get(that, prop) {
  2574. if (prop === 'clientWidth' && that[prop] > 1199)
  2575. return 1199;
  2576. return that[prop];
  2577. }
  2578. }));
  2579. },
  2580.  
  2581. // PopMix (both types of popups encountered on site)
  2582. 'openload.co': {
  2583. other: 'oload.tv, oload.info, openload.co.com',
  2584. now() {
  2585. if (inIFrame) {
  2586. nt.define('BetterJsPop', {
  2587. add(a, b) {
  2588. _console.trace('BetterJsPop.add(%o, %o)', a, b);
  2589. },
  2590. config(o) {
  2591. _console.trace('BetterJsPop.config(%o)', o);
  2592. },
  2593. Browser: {
  2594. isChrome: true
  2595. }
  2596. });
  2597. nt.define('isSandboxed', nt.func(null, 'isSandboxed'));
  2598. nt.define('adblock', false);
  2599. nt.define('adblock2', false);
  2600. } else preventPopMix();
  2601. }
  2602. },
  2603.  
  2604. 'turbobit.net': preventPopMix,
  2605.  
  2606. 'tapochek.net': () => {
  2607. // workaround for moradu.com/apu.php load error handler script, not sure which ad network is this
  2608. let _appendChild = Object.getOwnPropertyDescriptor(_Node, 'appendChild');
  2609. let _appendChild_value = _appendChild.value;
  2610. _appendChild.value = function appendChild(node) {
  2611. if (this === _document.body)
  2612. if ((node instanceof HTMLScriptElement || node instanceof HTMLStyleElement) &&
  2613. /^https?:\/\/[0-9a-f]{15}\.com\/\d+(\/|\.css)$/.test(node.src) ||
  2614. node instanceof HTMLDivElement && node.style.zIndex > 900000 &&
  2615. node.style.backgroundImage.includes('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'))
  2616. throw '...eenope!';
  2617. return _appendChild_value.apply(this, arguments);
  2618. };
  2619. Object.defineProperty(_Node, 'appendChild', _appendChild);
  2620.  
  2621. // disable window focus tricks and changing location
  2622. let focusHandlerName = /\WfocusAchieved\(/;
  2623. let _setInterval = win.setInterval;
  2624. win.setInterval = (...args) => {
  2625. if (args.length && focusHandlerName.test(_toString(args[0]))) {
  2626. _console.log('skip setInterval for', ...args);
  2627. return -1;
  2628. }
  2629. return _setInterval(...args);
  2630. };
  2631. let _addEventListener = win.addEventListener;
  2632. win.addEventListener = function (...args) {
  2633. if (args.length && args[0] === 'focus' && focusHandlerName.test(_toString(args[1]))) {
  2634. _console.log('skip addEventListener for', ...args);
  2635. return undefined;
  2636. }
  2637. return _addEventListener.apply(this, args);
  2638. };
  2639.  
  2640. // generic popup prevention
  2641. preventPopups();
  2642. },
  2643.  
  2644. // = other ======================================================================================
  2645.  
  2646. '1tv.ru': {
  2647. other: 'mediavitrina.ru',
  2648. now: () => scriptLander(() => {
  2649. nt.define('EUMPAntiblockConfig', nt.proxy({
  2650. url: '//www.1tv.ru/favicon.ico'
  2651. }));
  2652. nt.define('Object.prototype.disableSeek', nt.func(undefined, 'disableSeek'));
  2653. //nt.define('preroll', undefined);
  2654.  
  2655. let _EUMP;
  2656. const _EUMP_set = x => {
  2657. if (x === _EUMP)
  2658. return true;
  2659. let _plugins = x.plugins;
  2660. Object.defineProperty(x, 'plugins', {
  2661. enumerable: true,
  2662. get() {
  2663. return _plugins;
  2664. },
  2665. set(vl) {
  2666. if (vl === _plugins)
  2667. return true;
  2668. nt.defineOn(vl, 'antiblock', function (player, opts) {
  2669. const antiblock = nt.proxy({
  2670. opts: opts,
  2671. readyState: 'ready',
  2672. isEUMPPlugin: true,
  2673. detected: nt.func(false, 'antiblock.detected'),
  2674. currentWeight: nt.func(0, 'antiblock.currentWeight')
  2675. });
  2676. player.antiblock = antiblock;
  2677. return antiblock;
  2678. }, 'EUMP.plugins.');
  2679. _plugins = vl;
  2680. }
  2681. });
  2682. _EUMP = x;
  2683. return true;
  2684. };
  2685. if ('EUMP' in win)
  2686. _EUMP_set(win.EUMP);
  2687. Object.defineProperty(win, 'EUMP', {
  2688. enumerable: true,
  2689. get() {
  2690. return _EUMP;
  2691. },
  2692. set: _EUMP_set
  2693. });
  2694.  
  2695. let _EUMPVGTRK;
  2696. const _EUMPVGTRK_set = x => {
  2697. if (x === _EUMPVGTRK)
  2698. return true;
  2699. if (x && x.prototype) {
  2700. if ('generatePrerollUrls' in x.prototype)
  2701. nt.defineOn(x.prototype, 'generatePrerollUrls', nt.func(null, 'EUMPVGTRK.generatePrerollUrls'), 'EUMPVGTRK.prototype.', {
  2702. enumerable: false
  2703. });
  2704. if ('sendAdsEvent' in x.prototype)
  2705. nt.defineOn(x.prototype, 'sendAdsEvent', nt.func(null, 'EUMPVGTRK.sendAdsEvent'), 'EUMPVGTRK.prototype.', {
  2706. enumerable: false
  2707. });
  2708. }
  2709. _EUMPVGTRK = x;
  2710. return true;
  2711. };
  2712. if ('EUMPVGTRK' in win)
  2713. _EUMPVGTRK_set(win.EUMPVGTRK);
  2714. Object.defineProperty(win, 'EUMPVGTRK', {
  2715. enumerable: true,
  2716. get() {
  2717. return _EUMPVGTRK;
  2718. },
  2719. set: _EUMPVGTRK_set
  2720. });
  2721. }, nullTools)
  2722. },
  2723.  
  2724. '24smi.org': () => scriptLander(() => selectiveCookies('has_adblock'), selectiveCookies),
  2725.  
  2726. '2picsun.ru': {
  2727. other: 'pics2sun.ru, 3pics-img.ru',
  2728. now() {
  2729. Object.defineProperty(navigator, 'userAgent', {
  2730. value: 'googlebot'
  2731. });
  2732. }
  2733. },
  2734.  
  2735. '4pda.ru': {
  2736. now() {
  2737. // https://greasyfork.org/en/scripts/14470-4pda-unbrender
  2738. const isForum = location.pathname.startsWith('/forum/'),
  2739. remove = node => (node && node.parentNode.removeChild(node)),
  2740. hide = node => (node && (node.style.display = 'none'));
  2741.  
  2742. selectiveCookies('viewpref');
  2743. abortExecution.inlineScript('document.querySelector', {
  2744. pattern: /\(document(,window)?\);/
  2745. });
  2746.  
  2747. function cleaner(log) {
  2748. HeaderAds: {
  2749. // hide ads above HEADER
  2750. let nav = _document.querySelector('.menu-main-item');
  2751. while (nav && (nav.parentNode !== _de))
  2752. if (!nav.parentNode.querySelector('article, .container[itemtype$="Article"]'))
  2753. nav = nav.parentNode;
  2754. else break;
  2755. if (!nav || (nav.parentNode === _de)) {
  2756. if (log) _console.warn('Unable to locate header element');
  2757. break HeaderAds;
  2758. }
  2759. if (log) _console.log('Processing header:', nav);
  2760. for (let itm of nav.parentNode.children)
  2761. if (itm !== nav)
  2762. hide(itm);
  2763. else break;
  2764. }
  2765.  
  2766. FixNavMenu: {
  2767. // hide ad link from the navigation
  2768. let ad = _document.querySelector('.menu-main-item > a > svg');
  2769. if (!ad) {
  2770. if (log) _console.warn('Unable to locate menu ad item');
  2771. break FixNavMenu;
  2772. } else {
  2773. ad = ad.parentNode.parentNode;
  2774. hide(ad);
  2775. }
  2776. }
  2777.  
  2778. SidebarAds: {
  2779. // remove ads from sidebar
  2780. let aside = _document.querySelectorAll('[class]:not([id]) > [id]:not([class]) > :first-child + :last-child:not(.v-panel)');
  2781. if (!aside.length) {
  2782. if (log) _console.warn('Unable to locate sidebar');
  2783. break SidebarAds;
  2784. }
  2785. let post;
  2786. for (let side of aside) {
  2787. if (log) _console.log('Processing potential sidebar:', side);
  2788. for (let itm of Array.from(side.children)) {
  2789. post = itm.classList.contains('post');
  2790. if (post) continue;
  2791. if (itm.querySelector('iframe') || !itm.children.length)
  2792. remove(itm);
  2793. let script = itm.querySelector('script');
  2794. if (itm.querySelector('a[target="_blank"] > img') ||
  2795. script && script.src === '' && (script.type === 'text/javascript' || !script.type) &&
  2796. script.textContent.includes('document'))
  2797. hide(itm);
  2798. }
  2799. }
  2800. }
  2801. }
  2802.  
  2803. const cln = setInterval(() => cleaner(false), 50);
  2804.  
  2805. // hide banner next to logo
  2806. if (isForum)
  2807. createStyle('div[class]:not([id]) tr[valign="top"] > td:last-child { display: none !important }');
  2808. // clean page
  2809. window.addEventListener(
  2810. 'DOMContentLoaded',
  2811. function () {
  2812. clearInterval(cln);
  2813. const width = () => win.innerWidth || _de.clientWidth || _document.body.clientWidth || 0,
  2814. height = () => win.innerHeight || _de.clientHeight || _document.body.clientHeight || 0;
  2815.  
  2816. if (isForum) {
  2817. // hide banner next to logo
  2818. //let itm = _document.querySelector('#logostrip');
  2819. //if (itm) hide(itm.parentNode.nextSibling);
  2820. // clear background in the download frame
  2821. if (location.pathname.startsWith('/forum/dl/')) {
  2822. let setBackground = node => _setAttribute(
  2823. node,
  2824. 'style', (_getAttribute(node, 'style') || '') +
  2825. ';background-color:#4ebaf6!important'
  2826. );
  2827. setBackground(_document.body);
  2828. for (let itm of _document.querySelectorAll('body > div'))
  2829. if (!itm.querySelector('.dw-fdwlink, .content') && !itm.classList.contains('footer'))
  2830. remove(itm);
  2831. else
  2832. setBackground(itm);
  2833. }
  2834. // exist from DOMContentLoaded since the rest is not for forum
  2835. return;
  2836. }
  2837.  
  2838. cleaner(false);
  2839.  
  2840. _document.body.setAttribute('style', (_document.body.getAttribute('style') || '') + ';background-color:#E6E7E9!important');
  2841.  
  2842. let extra = 'background-image:none!important;background-color:transparent!important',
  2843. fakeStyles = new WeakMap(),
  2844. styleProxy = {
  2845. get(target, prop) {
  2846. return fakeStyles.get(target)[prop] || target[prop];
  2847. },
  2848. set(target, prop, value) {
  2849. let fakeStyle = fakeStyles.get(target);
  2850. ((prop in fakeStyle) ? fakeStyle : target)[prop] = value;
  2851. return true;
  2852. }
  2853. };
  2854. for (let itm of _document.querySelectorAll('[id]:not(A), A')) {
  2855. if (!(itm.offsetWidth > 0.95 * width() &&
  2856. itm.offsetHeight > 0.85 * height()))
  2857. continue;
  2858. if (itm.tagName !== 'A') {
  2859. fakeStyles.set(itm.style, {
  2860. 'backgroundImage': itm.style.backgroundImage,
  2861. 'backgroundColor': itm.style.backgroundColor
  2862. });
  2863.  
  2864. try {
  2865. Object.defineProperty(itm, 'style', {
  2866. value: new Proxy(itm.style, styleProxy),
  2867. enumerable: true
  2868. });
  2869. } catch (e) {
  2870. _console.log('Unable to protect style property.', e);
  2871. }
  2872.  
  2873. _setAttribute(itm, 'style', `${(_getAttribute(itm, 'style') || '')};${extra}`);
  2874. }
  2875. if (itm.tagName === 'A')
  2876. _setAttribute(itm, 'style', 'display:none!important');
  2877. }
  2878. }
  2879. );
  2880. }
  2881. },
  2882.  
  2883. 'adhands.ru': () => scriptLander(() => {
  2884. try {
  2885. let _adv;
  2886. Object.defineProperty(win, 'adv', {
  2887. get() {
  2888. return _adv;
  2889. },
  2890. set(val) {
  2891. _console.log('Blocked advert on adhands.ru.');
  2892. nt.defineOn(val, 'advert', '', 'adv.');
  2893. _adv = val;
  2894. }
  2895. });
  2896. } catch (ignore) {
  2897. if (!win.adv)
  2898. _console.log('Unable to locate advert on adhands.ru.');
  2899. else {
  2900. _console.log('Blocked advert on adhands.ru.');
  2901. nt.define('adv.advert', '');
  2902. }
  2903. }
  2904. }, nullTools),
  2905.  
  2906. 'all-episodes.org': () => {
  2907. nt.define('perROS', 0); // blocks access when = 1
  2908. nt.define('idm', -1); // blocks quality when >= 0
  2909. nt.define('advtss', nt.proxy({
  2910. offsetHeight: 200,
  2911. offsetWidth: 200
  2912. }, 'advtss'));
  2913. // wrap player to prevent some events and interactions
  2914. let _playerInstance = win.playerInstance;
  2915. Object.defineProperty(win, 'playerInstance', {
  2916. get() {
  2917. return _playerInstance;
  2918. },
  2919. set(vl) {
  2920. _console.log('player =', vl, vl.on, vl.getAdBlock);
  2921. vl.on = new Proxy(vl.on, {
  2922. apply(fun, that, args) {
  2923. if (/^(ad[A-Z]|before(Play|Complete))/.test(args[0]))
  2924. return;
  2925. //_console.log('on', ...args);
  2926. return _apply(fun, that, args);
  2927. }
  2928. });
  2929. nt.defineOn(vl, 'getAdBlock', nt.func(false, 'playerInstance.getAdBlock'), 'playerInstance.getAdBlock');
  2930. _playerInstance = vl;
  2931. }
  2932. });
  2933. },
  2934.  
  2935. 'allhentai.ru': () => {
  2936. preventPopups();
  2937. scriptLander(() => {
  2938. selectiveEval();
  2939. let _onerror = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onerror');
  2940. if (!_onerror)
  2941. return;
  2942. _onerror.set = (...args) => _console.log(args[0].toString());
  2943. Object.defineProperty(HTMLElement.prototype, 'onerror', _onerror);
  2944. }, selectiveEval);
  2945. },
  2946.  
  2947. 'allmovie.pro': {
  2948. other: 'rufilmtv.org',
  2949. dom() {
  2950. // pretend to be Android to make site use different played for ads
  2951. if (isSafari)
  2952. return;
  2953. Object.defineProperty(navigator, 'userAgent', {
  2954. get() {
  2955. 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';
  2956. },
  2957. enumerable: true
  2958. });
  2959. }
  2960. },
  2961.  
  2962. 'ati.su': () => scriptLander(() => {
  2963. nt.define('Object.prototype.advManager', nt.proxy({}, 'advManager'));
  2964. }),
  2965.  
  2966. 'audioportal.su': {
  2967. now() {
  2968. createStyle('#blink2 { display: none !important }');
  2969. },
  2970. dom() {
  2971. let links = _document.querySelectorAll('a[onclick*="clickme("]');
  2972. if (!links) return;
  2973. for (let link of links)
  2974. win.clickme(link);
  2975. }
  2976. },
  2977.  
  2978. 'auto.ru': () => {
  2979. let words = /Реклама|Яндекс.Директ|yandex_ad_/;
  2980. let userAdsListAds = (
  2981. '.listing-list > .listing-item,' +
  2982. '.listing-item_type_fixed.listing-item'
  2983. );
  2984. let catalogAds = (
  2985. 'div[class*="layout_catalog-inline"],' +
  2986. 'div[class$="layout_horizontal"]'
  2987. );
  2988. let otherAds = (
  2989. '.advt_auto,' +
  2990. '.sidebar-block,' +
  2991. '.pager-listing + div[class],' +
  2992. '.card > div[class][style],' +
  2993. '.sidebar > div[class],' +
  2994. '.main-page__section + div[class],' +
  2995. '.listing > tbody'
  2996. );
  2997. gardener(userAdsListAds, words, {
  2998. root: '.listing-wrap',
  2999. observe: true
  3000. });
  3001. gardener(catalogAds, words, {
  3002. root: '.catalog__page,.content__wrapper',
  3003. observe: true
  3004. });
  3005. gardener(otherAds, words);
  3006. nt.define('Object.prototype.yaads', undefined);
  3007. nt.define('Object.prototype.initYaDirect', undefined);
  3008. nt.define('Object.prototype.direct', nt.proxy({}, 'Yandex.direct'));
  3009. },
  3010.  
  3011. 'avito.ru': () => scriptLander(() => selectiveCookies('abp|cmtchd|crookie|is_adblock'), selectiveCookies),
  3012.  
  3013. 'di.fm': () => scriptLander(() => {
  3014. let log = false;
  3015. // wrap global app object to catch registration of specific modules
  3016. let _di = win.di;
  3017. Object.defineProperty(win, 'di', {
  3018. get() {
  3019. return _di;
  3020. },
  3021. set(vl) {
  3022. if (vl === _di)
  3023. return;
  3024. if (log) _console.trace('di =', vl);
  3025. _di = new Proxy(vl, {
  3026. set(di, name, vl) {
  3027. if (vl === di[name])
  3028. return true;
  3029. if (name === 'app') {
  3030. if (log) _console.trace(`di.${name} =`, vl);
  3031. if (!('module' in vl))
  3032. return;
  3033. vl.module = new Proxy(vl.module, {
  3034. apply(module, that, args) {
  3035. if (/Wall|Banner|Detect|WebplayerApp\.Ads/.test(args[0])) {
  3036. let name = args[0];
  3037. if (log) _console.log('wrap', name, 'module');
  3038. if (typeof args[1] === 'function')
  3039. args[1] = new Proxy(args[1], {
  3040. apply(fun, that, args) {
  3041. if (args[0]) // module object
  3042. args[0].start = () => _console.log('Skipped start of', name);
  3043. return Reflect.apply(fun, that, args);
  3044. }
  3045. });
  3046. } // else log && _console.log('loading module', args[0]);
  3047. if (args[0] === 'Modals' && typeof args[1] === 'function') {
  3048. if (log) _console.log('wrap', name, 'module');
  3049. args[1] = new Proxy(args[1], {
  3050. apply(fun, that, args) {
  3051. if ('commands' in args[1] && 'setHandlers' in args[1].commands &&
  3052. !Object.hasOwnProperty.call(args[1].commands, 'setHandlers')) {
  3053. let _commands = args[1].commands;
  3054. _commands.setHandlers = new Proxy(_commands.setHandlers, {
  3055. apply(fun, that, args) {
  3056. const noopFunc = name => () => _console.log('Skipped', name, 'window');
  3057. for (let name in args[0])
  3058. if (name === 'modal:streaminterrupt' ||
  3059. name === 'modal:midroll')
  3060. args[0][name] = noopFunc(name);
  3061. delete _commands.setHandlers;
  3062. return Reflect.apply(fun, that, args);
  3063. }
  3064. });
  3065. }
  3066. return Reflect.apply(fun, that, args);
  3067. }
  3068. });
  3069. }
  3070. return Reflect.apply(module, that, args);
  3071. }
  3072. });
  3073. }
  3074. di[name] = vl;
  3075. }
  3076. });
  3077. }
  3078. });
  3079. // don't send errorception logs
  3080. Object.defineProperty(win, 'onerror', {
  3081. set(vl) {
  3082. if (log) _console.trace('Skipped global onerror callback:', vl);
  3083. }
  3084. });
  3085. }),
  3086.  
  3087. 'draug.ru': {
  3088. other: 'vargr.ru',
  3089. now: () => scriptLander(() => {
  3090. if (location.pathname === '/pop.html')
  3091. win.close();
  3092. createStyle({
  3093. '#timer_1': {
  3094. display: 'none !important'
  3095. },
  3096. '#timer_2': {
  3097. display: 'block !important'
  3098. }
  3099. });
  3100. let _contentWindow = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, 'contentWindow');
  3101. let _get_contentWindow = _bindCall(_contentWindow.get);
  3102. _contentWindow.get = function () {
  3103. let res = _get_contentWindow(this);
  3104. if (res.location.href === 'about:blank')
  3105. res.document.write = (...args) => _console.log('Skipped iframe.write(', ...args, ')');
  3106. return res;
  3107. };
  3108. Object.defineProperty(HTMLIFrameElement.prototype, 'contentWindow', _contentWindow);
  3109. }),
  3110. dom() {
  3111. let list = _querySelectorAll('div[id^="yandex_rtb_"], .adsbygoogle');
  3112. list.forEach(node => _console.log('Removed:', node.parentNode.parentNode.removeChild(node.parentNode)));
  3113. }
  3114. },
  3115.  
  3116. 'drive2.ru': () => {
  3117. gardener('.c-block:not([data-metrika="recomm"]),.o-grid__item', />Реклама<\//i);
  3118. scriptLander(() => {
  3119. selectiveCookies();
  3120. let _d2;
  3121. Object.defineProperty(win, 'd2', {
  3122. get() {
  3123. return _d2;
  3124. },
  3125. set(vl) {
  3126. if (vl === _d2)
  3127. return true;
  3128. _d2 = new Proxy(vl, {
  3129. set(target, prop, val) {
  3130. if (['brandingRender', 'dvReveal', '__dv'].includes(prop))
  3131. val = () => null;
  3132. target[prop] = val;
  3133. return true;
  3134. }
  3135. });
  3136. }
  3137. });
  3138. // obfuscated Yandex.Direct
  3139. nt.define('Object.prototype.initYaDirect', undefined);
  3140. }, nullTools, selectiveCookies);
  3141. },
  3142.  
  3143. 'eurogamer.tld': {
  3144. other: 'metabomb.net, usgamer.net',
  3145. now: () => scriptLander(() => {
  3146. abortExecution.inlineScript('_sp_');
  3147. selectiveCookies('sp');
  3148. }, selectiveCookies, abortExecution)
  3149. },
  3150.  
  3151. 'fastpic.ru': () => {
  3152. // Had to obfuscate property name to avoid triggering anti-obfuscation on greasyfork.org -_- (Exception 403012)
  3153. nt.define(`_0x${'4955'}`, []);
  3154. },
  3155.  
  3156. 'fishki.net': () => {
  3157. scriptLander(() => {
  3158. const fishki = {};
  3159. const adv = nt.proxy({
  3160. afterAdblockCheck: nt.func(null, 'fishki.afterAdblockCheck'),
  3161. refreshFloat: nt.func(null, 'fishki.refreshFloat')
  3162. });
  3163. nt.defineOn(fishki, 'adv', adv, 'fishki.');
  3164. nt.defineOn(fishki, 'is_adblock', false, 'fishki.');
  3165. nt.define('fishki', fishki);
  3166. nt.define('Object.prototype.detect', nt.func(undefined, 'detect'));
  3167. win.Object.defineProperty = new Proxy(win.Object.defineProperty, {
  3168. apply(fun, that, args) {
  3169. if (['is_adblock', 'adv'].includes(args[1]) || args[0] === adv)
  3170. return;
  3171. return _apply(fun, that, args);
  3172. }
  3173. });
  3174. }, nullTools);
  3175. gardener('.drag_list > .drag_element, .list-view > .paddingtop15, .post-wrap', /543769|Новости\sпартнеров|Полезная\sреклама/);
  3176. },
  3177.  
  3178. 'forbes.com': () => {
  3179. createStyle(['fbs-ad[ad-id], .top-ad-container, .fbs-ad-wrapper, .footer-ad-labeling, .ad-rail, .ad-unit { display: none !important; }']);
  3180. nt.define('Object.prototype.isAdLight', true);
  3181. nt.define('Object.prototype.initializeAd', nt.func(undefined, '?.initializeAd'));
  3182. win.getComputedStyle = new Proxy(win.getComputedStyle, {
  3183. apply(fun, that, args) {
  3184. let res = _apply(fun, that, args);
  3185. if (res.display === 'none')
  3186. nt.defineOn(res, 'display', 'block', 'getComputedStyle().');
  3187. if (res.visibility === 'hidden')
  3188. nt.defineOn(res, 'visibility', 'visible', 'getComputedStyle().');
  3189. return res;
  3190. }
  3191. });
  3192. win.CSSStyleDeclaration.prototype.getPropertyValue = new Proxy(win.CSSStyleDeclaration.prototype.getPropertyValue, {
  3193. apply(fun, that, args) {
  3194. let res = _apply(fun, that, args);
  3195. if (args[0] === 'display' && res === 'none')
  3196. return 'block';
  3197. if (args[0] === 'visibility' && res === 'hidden')
  3198. return 'visible';
  3199. return res;
  3200. }
  3201. });
  3202. },
  3203.  
  3204. 'friends.in.ua': () => scriptLander(() => {
  3205. Object.defineProperty(win, 'need_warning', {
  3206. get() {
  3207. return 0;
  3208. },
  3209. set() {}
  3210. });
  3211. }),
  3212.  
  3213. 'gamerevolution.com': () => {
  3214. const _clientHeight = Object.getOwnPropertyDescriptor(_Element, 'clientHeight');
  3215. _clientHeight.get = new Proxy(_clientHeight.get, {
  3216. apply(...args) {
  3217. return _apply(...args) || 1;
  3218. }
  3219. });
  3220. Object.defineProperty(_Element, 'clientHeight', _clientHeight);
  3221.  
  3222. const toReplace = [
  3223. 'blockerDetected', 'disableDetected', 'hasAdBlocker',
  3224. 'hasBlockerFlag', 'hasDisabledAdBlocker', 'hasBlocker'
  3225. ];
  3226. win.Object.defineProperty = new Proxy(win.Object.defineProperty, {
  3227. apply(fun, that, args) {
  3228. if (toReplace.includes(args[1])) {
  3229. args[2] = {
  3230. value() {
  3231. return false;
  3232. }
  3233. };
  3234. console.log(args);
  3235. }
  3236. return _apply(fun, that, args);
  3237. }
  3238. });
  3239. },
  3240.  
  3241. 'gamersheroes.com': () => abortExecution.inlineScript('document.createElement', {
  3242. pattern: /window\[\w+\(\[(\d+,?\s?)+\],\s?\w+\)\]/
  3243. }),
  3244.  
  3245. 'gidonline.club': () => createStyle('.tray > div[style] {display: none!important}'),
  3246.  
  3247. 'glav.su': () => scriptLander(() => {
  3248. abortExecution.onSet('abd');
  3249. abortExecution.onSet('script1');
  3250. }, abortExecution),
  3251.  
  3252. 'gorodrabot.ru': () => scriptLander(() => {
  3253. abortExecution.onGet('Object.prototype.yaads');
  3254. abortExecution.onGet('Object.prototype.initYaDirect');
  3255. }, abortExecution),
  3256.  
  3257. 'hdgo.cc': {
  3258. other: '46.30.43.38, couber.be',
  3259. now() {
  3260. (new MutationObserver(
  3261. ms => {
  3262. let m, node;
  3263. for (m of ms)
  3264. for (node of m.addedNodes)
  3265. if (node.tagName instanceof HTMLScriptElement && _getAttribute(node, 'onerror') !== null)
  3266. node.removeAttribute('onerror');
  3267. }
  3268. )).observe(_document.documentElement, {
  3269. childList: true,
  3270. subtree: true
  3271. });
  3272. }
  3273. },
  3274.  
  3275. 'gamepur.com': () => {
  3276. nt.define('ga', nt.func(null, 'ga'));
  3277. win.Object.defineProperty = new Proxy(win.Object.defineProperty, {
  3278. apply(fun, that, args) {
  3279. if (typeof args[1] === 'string' &&
  3280. (args[1] === 'hasAdblocker' || args[1] === 'blockerDetected'))
  3281. throw new TypeError(`Cannot read property '${args[1]}' of undefined`);
  3282. return Reflect.apply(fun, that, args);
  3283. }
  3284. });
  3285. },
  3286.  
  3287. 'hdrezka.ag': () => {
  3288. Object.defineProperty(win, 'ab', {
  3289. value: false,
  3290. enumerable: true
  3291. });
  3292. gardener('div[id][onclick][onmouseup][onmousedown]', /onmouseout/i);
  3293. },
  3294.  
  3295. 'htmlweb.ru': () => {
  3296. let _onerror = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onerror');
  3297. _onerror.set = new Proxy(_onerror.set, {
  3298. apply(fun, that, args) {
  3299. if (that.tagName === 'SCRIPT')
  3300. return _console.log('Skip set onerror for', that);
  3301. return _apply(fun, that, args);
  3302. }
  3303. });
  3304. Object.defineProperty(HTMLElement.prototype, 'onerror', _onerror);
  3305. },
  3306.  
  3307. 'hqq.tv': () => scriptLander(() => {
  3308. // disable anti-debugging in hqq.tv player
  3309. 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);
  3310. deepWrapAPI(root => {
  3311. // skip obfuscated stuff and a few other calls
  3312. let _setInterval = root.setInterval,
  3313. _setTimeout = root.setTimeout;
  3314. root.setInterval = (...args) => {
  3315. let fun = args[0];
  3316. if (typeof fun === 'function') {
  3317. let text = _toString(fun),
  3318. skip = text.includes('check();') || isObfuscated(text);
  3319. _console.trace('setInterval', text, 'skip', skip);
  3320. if (skip) return -1;
  3321. }
  3322. return _setInterval.apply(this, args);
  3323. };
  3324. let wrappedST = new WeakSet();
  3325. root.setTimeout = (...args) => {
  3326. let fun = args[0];
  3327. if (typeof fun === 'function') {
  3328. let text = _toString(fun),
  3329. skip = fun.name === 'check' || isObfuscated(text);
  3330. if (!wrappedST.has(fun)) {
  3331. _console.trace('setTimeout', text, 'skip', skip);
  3332. wrappedST.add(fun);
  3333. }
  3334. if (skip) return;
  3335. }
  3336. return _setTimeout.apply(this, args);
  3337. };
  3338. // skip 'debugger' call
  3339. let _eval = root.eval;
  3340. root.eval = text => {
  3341. if (typeof text === 'string' && text.includes('debugger;')) {
  3342. _console.trace('skip eval', text);
  3343. return;
  3344. }
  3345. _eval(text);
  3346. };
  3347. // Prevent RegExpt + toString trick
  3348. let _proto;
  3349. try {
  3350. _proto = root.RegExp.prototype;
  3351. } catch (ignore) {
  3352. return;
  3353. }
  3354. let _RE_tS = Object.getOwnPropertyDescriptor(_proto, 'toString');
  3355. let _RE_tSV = _RE_tS.value || _RE_tS.get();
  3356. Object.defineProperty(_proto, 'toString', {
  3357. enumerable: _RE_tS.enumerable,
  3358. configurable: _RE_tS.configurable,
  3359. get() {
  3360. return _RE_tSV;
  3361. },
  3362. set(val) {
  3363. _console.trace('Attempt to change toString for', this, 'with', _toString(val));
  3364. }
  3365. });
  3366. });
  3367. }, deepWrapAPI),
  3368.  
  3369. 'hideip.me': {
  3370. now: () => scriptLander(() => {
  3371. let _innerHTML = Object.getOwnPropertyDescriptor(_Element, 'innerHTML');
  3372. let _set_innerHTML = _innerHTML.set;
  3373. let _innerText = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'innerText');
  3374. let _get_innerText = _innerText.get;
  3375. let div = _document.createElement('div');
  3376. _innerHTML.set = function (...args) {
  3377. _set_innerHTML.call(div, args[0].replace('i', 'a'));
  3378. if (args[0] && /[рp][еe]кл/.test(_get_innerText.call(div)) ||
  3379. /(\d\d\d?\.){3}\d\d\d?:\d/.test(_get_innerText.call(this))) {
  3380. _console.log('Anti-Adblock killed.');
  3381. return true;
  3382. }
  3383. _set_innerHTML.apply(this, args);
  3384. };
  3385. Object.defineProperty(_Element, 'innerHTML', _innerHTML);
  3386. Object.defineProperty(win, 'adblock', {
  3387. get() {
  3388. return false;
  3389. },
  3390. set() {},
  3391. enumerable: true
  3392. });
  3393. let _$ = {};
  3394. let _$_map = new WeakMap();
  3395. let _gOPD = Object.getOwnPropertyDescriptor(Object, 'getOwnPropertyDescriptor');
  3396. let _val_gOPD = _gOPD.value;
  3397. _gOPD.value = function (...args) {
  3398. let _res = _val_gOPD.apply(this, args);
  3399. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery')) {
  3400. delete _res.get;
  3401. delete _res.set;
  3402. _res.value = win[args[1]];
  3403. }
  3404. return _res;
  3405. };
  3406. Object.defineProperty(Object, 'getOwnPropertyDescriptor', _gOPD);
  3407. let getJQWrap = (n) => {
  3408. let name = n;
  3409. return {
  3410. enumerable: true,
  3411. get() {
  3412. return _$[name];
  3413. },
  3414. set(x) {
  3415. if (_$_map.has(x)) {
  3416. _$[name] = _$_map.get(x);
  3417. return true;
  3418. }
  3419. if (x === _$.$ || x === _$.jQuery) {
  3420. _$[name] = x;
  3421. return true;
  3422. }
  3423. _$[name] = new Proxy(x, {
  3424. apply(t, o, args) {
  3425. let _res = t.apply(o, args);
  3426. if (_$_map.has(_res.is))
  3427. _res.is = _$_map.get(_res.is);
  3428. else {
  3429. let _is = _res.is;
  3430. _res.is = function (...args) {
  3431. if (args[0] === ':hidden')
  3432. return false;
  3433. return _is.apply(this, args);
  3434. };
  3435. _$_map.set(_is, _res.is);
  3436. }
  3437. return _res;
  3438. }
  3439. });
  3440. _$_map.set(x, _$[name]);
  3441. return true;
  3442. }
  3443. };
  3444. };
  3445. Object.defineProperty(win, '$', getJQWrap('$'));
  3446. Object.defineProperty(win, 'jQuery', getJQWrap('jQuery'));
  3447. let _dP = Object.defineProperty;
  3448. Object.defineProperty = function (...args) {
  3449. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery'))
  3450. return undefined;
  3451. return _dP.apply(this, args);
  3452. };
  3453. })
  3454. },
  3455.  
  3456. 'igra-prestoloff.cx': () => scriptLander(() => {
  3457. /*jslint evil: true */ // yes, evil, I know
  3458. let _write = _document.write.bind(_document);
  3459. /*jslint evil: false */
  3460. nt.define('document.write', t => {
  3461. let id = t.match(/jwplayer\("(\w+)"\)/i);
  3462. if (id && id[1])
  3463. return _write(`<div id="${id[1]}"></div>${t}`);
  3464. return _write('');
  3465. }, {
  3466. enumerable: true
  3467. });
  3468. }),
  3469.  
  3470. 'imageban.ru': () => {
  3471. Object.defineProperty(win, 'V7x1J', {
  3472. get() {
  3473. return null;
  3474. }
  3475. });
  3476. },
  3477.  
  3478. 'inoreader.com': () => scriptLander(() => {
  3479. let i = setInterval(() => {
  3480. if ('adb_detected' in win) {
  3481. win.adb_detected = () => win.adb_not_detected();
  3482. clearInterval(i);
  3483. }
  3484. }, 10);
  3485. _document.addEventListener('DOMContentLoaded', () => clearInterval(i), false);
  3486. }),
  3487.  
  3488. 'it-actual.ru': () => scriptLander(() => {
  3489. abortExecution.onAll('blocked');
  3490. abortExecution.onGet('nsg');
  3491. }, abortExecution),
  3492.  
  3493. 'ivi.ru': () => {
  3494. let _xhr_open = win.XMLHttpRequest.prototype.open;
  3495. win.XMLHttpRequest.prototype.open = function (method, url, ...args) {
  3496. if (typeof url === 'string')
  3497. if (url.endsWith('/track'))
  3498. return;
  3499. return _xhr_open.call(this, method, url, ...args);
  3500. };
  3501. let _responseText = Object.getOwnPropertyDescriptor(XMLHttpRequest.prototype, 'responseText');
  3502. let _responseText_get = _responseText.get;
  3503. _responseText.get = function () {
  3504. if (this.__responseText__)
  3505. return this.__responseText__;
  3506. let res = _responseText_get.apply(this, arguments);
  3507. let o;
  3508. try {
  3509. if (res)
  3510. o = JSON.parse(res);
  3511. } catch (ignore) {}
  3512. let changed = false;
  3513. if (o && o.result) {
  3514. if (o.result instanceof Array &&
  3515. 'adv_network_logo_url' in o.result[0]) {
  3516. o.result = [];
  3517. changed = true;
  3518. }
  3519. if (o.result.show_adv) {
  3520. o.result.show_adv = false;
  3521. changed = true;
  3522. }
  3523. }
  3524. if (changed) {
  3525. _console.log('changed response >>', o);
  3526. res = JSON.stringify(o);
  3527. }
  3528. this.__responseText__ = res;
  3529. return res;
  3530. };
  3531. Object.defineProperty(XMLHttpRequest.prototype, 'responseText', _responseText);
  3532. },
  3533.  
  3534. 'kakprosto.ru': () => scriptLander(() => {
  3535. selectiveCookies('yadb');
  3536. abortExecution.inlineScript('yaProxy', {
  3537. pattern: /yadb/
  3538. });
  3539. abortExecution.inlineScript('yandexContextAsyncCallbacks');
  3540. abortExecution.inlineScript('adfoxAsyncParams');
  3541. abortExecution.inlineScript('adfoxBackGroundLoaded');
  3542. }, selectiveCookies, abortExecution),
  3543.  
  3544. 'kinopoisk.ru': () => {
  3545. // filter cookies
  3546. // set no-branding body style and adjust other blocks on the page
  3547. const style = {
  3548. '.app__header.app__header_margin-bottom_brand, #top': {
  3549. margin_bottom: '20px !important'
  3550. },
  3551. '.app__branding': {
  3552. display: 'none!important'
  3553. }
  3554. };
  3555. if (location.hostname === 'www.kinopoisk.ru' && !location.pathname.startsWith('/games/'))
  3556. style['html:not(#id), body:not(#id), .app-container'] = {
  3557. background: '#d5d5d5 url(/images/noBrandBg.jpg) 50% 0 no-repeat !important'
  3558. };
  3559. createStyle(style);
  3560. scriptLander(() => {
  3561. selectiveCookies('cmtchd|crookie|kpunk');
  3562. // filter JSON
  3563. win.JSON.parse = new Proxy(win.JSON.parse, {
  3564. apply(fun, that, args) {
  3565. let o = _apply(fun, that, args);
  3566. let name = 'antiAdBlockCookieName';
  3567. if (name in o && typeof o[name] === 'string')
  3568. selectiveCookies(o[name]);
  3569. name = 'branding';
  3570. if (name in o) o[name] = {};
  3571. // tricks against ads in the trailer player
  3572. // if (location.hostname.startsWith('widgets.'))
  3573. if (o.page && o.page.playerParams)
  3574. delete o.page.playerParams.adConfig;
  3575. if (o.common && o.common.bunker && o.common.bunker.adv && o.common.bunker.adv.filmIdWithoutAd)
  3576. o.common.bunker.adv.filmIdWithoutAd.includes = () => true;
  3577. //_console.log('JSON.parse', o);
  3578. return o;
  3579. }
  3580. });
  3581. // skip timeout check for blocked requests
  3582. win.setTimeout = new Proxy(win.setTimeout, {
  3583. apply(fun, that, args) {
  3584. if (args[1] === 100) {
  3585. let str = _toString(args[0]);
  3586. if (str.endsWith('{a()}') || str.endsWith('{n()}'))
  3587. return;
  3588. }
  3589. return _apply(fun, that, args);
  3590. }
  3591. });
  3592. // obfuscated Yandex.Direct
  3593. nt.define('Object.prototype.initYaDirect', undefined);
  3594. nt.define('Object.prototype._resolveDetectResult', () => null);
  3595. nt.define('Object.prototype.detectResultPromise', new Promise(r => r(false)));
  3596. if (location.hostname === 'www.kinopoisk.ru')
  3597. nt.define('Object.prototype.initAd', nt.func(undefined, 'initAd'));
  3598. // catch branding and other things
  3599. let _KP;
  3600. Object.defineProperty(win, 'KP', {
  3601. get() {
  3602. return _KP;
  3603. },
  3604. set(val) {
  3605. if (_KP === val)
  3606. return true;
  3607. _KP = new Proxy(val, {
  3608. set(kp, name, val) {
  3609. if (name === 'branding') {
  3610. kp[name] = new Proxy({
  3611. weborama: {}
  3612. }, {
  3613. get(kp, name) {
  3614. return name in kp ? kp[name] : '';
  3615. },
  3616. set() {}
  3617. });
  3618. return true;
  3619. }
  3620. if (name === 'config')
  3621. val = new Proxy(val, {
  3622. set(cfg, name, val) {
  3623. if (name === 'anContextUrl')
  3624. return true;
  3625. if (name === 'adfoxEnabled' || name === 'hasBranding')
  3626. val = false;
  3627. if (name === 'adfoxVideoAdUrls')
  3628. val = {
  3629. flash: {},
  3630. html: {}
  3631. };
  3632. cfg[name] = val;
  3633. return true;
  3634. }
  3635. });
  3636. kp[name] = val;
  3637. return true;
  3638. }
  3639. });
  3640. _console.log('KP =', val);
  3641. }
  3642. });
  3643. }, selectiveCookies, nullTools);
  3644. },
  3645.  
  3646. 'korrespondent.net': {
  3647. now: () => scriptLander(() => {
  3648. nt.define('holder', function (id) {
  3649. let div = _document.getElementById(id);
  3650. if (!div)
  3651. return;
  3652. if (div.parentNode.classList.contains('col__sidebar')) {
  3653. div.parentNode.appendChild(div);
  3654. div.style.height = '300px';
  3655. }
  3656. });
  3657. }, nullTools),
  3658. dom() {
  3659. for (let frame of _document.querySelectorAll('.unit-side-informer > iframe'))
  3660. frame.parentNode.style.width = '1px';
  3661. }
  3662. },
  3663.  
  3664. 'libertycity.ru': () => scriptLander(() => {
  3665. nt.define('adBlockEnabled', false);
  3666. }, nullTools),
  3667.  
  3668. 'liveinternet.ru': () => scriptLander(() => {
  3669. abortExecution.onGet('Object.prototype.initAd');
  3670. }, abortExecution),
  3671.  
  3672. 'livejournal.com': () => scriptLander(() => {
  3673. nt.define('Object.prototype.Adf', undefined);
  3674. nt.define('Object.prototype.Begun', undefined);
  3675. }, nullTools),
  3676.  
  3677. 'mail.ru': {
  3678. other: 'ok.ru, sportmail.ru',
  3679. now: () => scriptLander(() => {
  3680. const _hostparts = location.hostname.split('.');
  3681. const _subdomain = _hostparts.slice(-3).join('.');
  3682. const _hostname = _hostparts.slice(-2).join('.');
  3683. const _emailru = _subdomain === 'e.mail.ru' || _subdomain === 'octavius.mail.ru';
  3684. const _mymailru = _subdomain === 'my.mail.ru';
  3685. const _okru = _hostname === 'ok.ru';
  3686. // setTimeout filter
  3687. // advBlock|rbParams - ads
  3688. // document\.title= - blinking title on background news load on main page
  3689. const pattern = /advBlock|rbParams|document\.title=/i;
  3690. const _setTimeout = win.setTimeout;
  3691. win.setTimeout = function setTimeout(...args) {
  3692. let text = _toString(args[0]);
  3693. if (pattern.test(text)) {
  3694. _console.trace('Skipped setTimeout:', text);
  3695. return;
  3696. }
  3697. return _setTimeout(...args);
  3698. };
  3699.  
  3700. // Trick to prevent mail.ru from removing 3rd-party styles
  3701. nt.define('Object.prototype.restoreVisibility', nt.func(null, 'restoreVisibility'));
  3702. // Other Yandex Direct and other ads
  3703. nt.define('Object.prototype.initMimic', undefined);
  3704. nt.define('Object.prototype.hpConfig', undefined);
  3705. nt.define('Object.prototype.direct', undefined);
  3706. const getAds = () => new Promise(
  3707. r => r(nt.proxy({}, '?.getAds()'))
  3708. );
  3709. nt.define('Object.prototype.getAds', getAds);
  3710. nt.define('rb_counter', nt.func(null, 'rb_counter'));
  3711. if (_subdomain === 'mail.ru') { // main page
  3712. nt.define('Object.prototype.baits', undefined); // detector
  3713. nt.define('Object.prototype.getFeed', nt.func(null, 'pulse.getFeed')); // Pulse feed
  3714. createStyle('body > div > .pulse { display: none !important }');
  3715. }
  3716. if (_emailru)
  3717. nt.define('Object.prototype.show_me_ads', undefined);
  3718. else if (_mymailru)
  3719. nt.define('Object.prototype.runMimic', nt.func(null, 'runMimic'));
  3720. else {
  3721. nt.define('Object.prototype.mimic', undefined);
  3722. const xray = nt.func(undefined, 'xray');
  3723. nt.defineOn(xray, 'send', nt.func(undefined, 'xray.send'), 'xray.');
  3724. nt.defineOn(xray, 'radarPrefix', null, 'xray.');
  3725. nt.defineOn(xray, 'xrayRadarUrl', undefined, 'xray.');
  3726. nt.defineOn(xray, 'defaultParams', nt.proxy({
  3727. i: undefined,
  3728. p: 'media'
  3729. }), 'xray.');
  3730. nt.define('Object.prototype.xray', nt.proxy(xray));
  3731. }
  3732. // shenanigans against ok.ru ABP detector
  3733. if (_okru) {
  3734. abortExecution.onGet('OK.hooks');
  3735. // banners on ok.ru and counter
  3736. nt.define('getAdvTargetParam', nt.func(null, 'getAdvTargetParam'));
  3737. // break detection in case detector wasn't wrapped
  3738. abortExecution.onSet('Object.prototype.adBlockDetected');
  3739. }
  3740. // news.mail.ru and sportmail.ru
  3741. abortExecution.onGet('myWidget');
  3742. // cleanup e.mail.ru configs and mimic config on news and sport
  3743. const emptyString = (root, name) => root[name] && (root[name] = '');
  3744. const detectMimic = /direct|240x400|SlotView/;
  3745. win.JSON.parse = new Proxy(win.JSON.parse, {
  3746. apply(fun, that, args) {
  3747. let o = _apply(fun, that, args);
  3748. if (o && typeof o === 'object') {
  3749. if (o.cfg && o.cfg.sotaFeatures) {
  3750. let root = o.cfg.sotaFeatures;
  3751. if (Array.isArray(root.adv)) root.adv = [];
  3752. for (let name in root)
  3753. if (name.startsWith('adv-') || name.startsWith('adman-'))
  3754. delete root[name];
  3755. ['email_logs_to', 'smokescreen-locators'].forEach(name => emptyString(root, name));
  3756. }
  3757. if (o.userConfig) {
  3758. if (Array.isArray(o.userConfig.honeypot))
  3759. o.userConfig.honeypot.forEach((v, id, me) => (me[id] = []));
  3760. const cfg = o.userConfig.config;
  3761. if (cfg && cfg.honeypot)
  3762. emptyString(cfg.honeypot, 'baits');
  3763. }
  3764. if (o.body) {
  3765. const flags = o.body.common_purpose_flags;
  3766. if (flags && 'hide_ad_in_mail_web' in flags)
  3767. flags.hide_ad_in_mail_web = true;
  3768. if (o.body.show_me_ads)
  3769. o.body.show_me_ads = false;
  3770. }
  3771. //_console.log('JSON.parse', o);
  3772. }
  3773. if (Array.isArray(o))
  3774. if (o.some(t => typeof t === 'string' && detectMimic.test(t))) {
  3775. _console.log('Replaced', o);
  3776. o = [];
  3777. } //else _console.log('JSON.parse', o);
  3778. return o;
  3779. }
  3780. });
  3781. // all the rest is only needed on main page and in emails
  3782. if (_subdomain !== 'mail.ru' && !_emailru && !_okru)
  3783. return;
  3784.  
  3785. // Disable page scrambler on mail.ru to let extensions easily block ads there
  3786. let logger = {
  3787. apply(fun, that, args) {
  3788. let res = _apply(fun, that, args);
  3789. _console.log(`${fun._name}(`, ...args, `)\n>>`, res);
  3790. return res;
  3791. }
  3792. };
  3793.  
  3794. function wrapLocator(locator) {
  3795. if ('setup' in locator) {
  3796. let _setup = locator.setup;
  3797. locator.setup = function (o) {
  3798. if ('enable' in o) {
  3799. o.enable = false;
  3800. _console.log('Disable mimic mode.');
  3801. }
  3802. if ('links' in o) {
  3803. o.links = [];
  3804. _console.log('Call with empty list of sheets.');
  3805. }
  3806. return _setup.call(this, o);
  3807. };
  3808. locator.insertSheet = () => false;
  3809. locator.wrap = () => false;
  3810. }
  3811. try {
  3812. let names = [];
  3813. for (let name in locator)
  3814. if (typeof locator[name] === 'function' && name !== 'transform') {
  3815. locator[name]._name = "locator." + name;
  3816. locator[name] = new Proxy(locator[name], logger);
  3817. names.push(name);
  3818. }
  3819. _console.log(`[locator] wrapped properties: ${names.length ? names.join(', ') : '[empty]'}`);
  3820. } catch (e) {
  3821. _console.log(e);
  3822. }
  3823. return locator;
  3824. }
  3825.  
  3826. function defineLocator(root) {
  3827. let _locator = root.locator;
  3828. let wrapLocatorSetter = vl => _locator = wrapLocator(vl);
  3829. let loc_desc = Object.getOwnPropertyDescriptor(root, 'locator');
  3830. if (!loc_desc || loc_desc.set !== wrapLocatorSetter)
  3831. try {
  3832. Object.defineProperty(root, 'locator', {
  3833. set: wrapLocatorSetter,
  3834. get() {
  3835. return _locator;
  3836. }
  3837. });
  3838. } catch (err) {
  3839. _console.log('Unable to redefine "locator" object!!!', err);
  3840. }
  3841. if (loc_desc.value)
  3842. _locator = wrapLocator(loc_desc.value);
  3843. }
  3844.  
  3845. { // auto-stubs for various ad, detection and obfuscation modules
  3846. const missingCheck = {
  3847. get(obj, name) {
  3848. let res = obj[name];
  3849. if (!(name in obj))
  3850. _console.trace(`Missing "${name}" in`, obj);
  3851. return res;
  3852. }
  3853. };
  3854. const skipLog = (name, ret) => (...args) => (_console.log(`${name}(`, ...args, ')'), ret);
  3855. const createSkipAllObject = (baseName, obj = {
  3856. __esModule: true
  3857. }) => new Proxy(obj, {
  3858. get(obj, name) {
  3859. if (name in obj)
  3860. return obj[name];
  3861. _console.log(`Created stub for "${name}" in ${baseName}.`);
  3862. obj[name] = skipLog(`${baseName}.${name}`);
  3863. return obj[name];
  3864. },
  3865. set() {}
  3866. });
  3867. const redefiner = {
  3868. apply(fun, that, args) {
  3869. let res;
  3870. let warn = false;
  3871. let name = fun._name;
  3872. if (name === 'mrg-smokescreen/Welter')
  3873. res = {
  3874. isWelter() {
  3875. return true;
  3876. },
  3877. wrap: skipLog(`${name}.wrap`)
  3878. };
  3879. if (name === 'mrg-smokescreen/Honeypot')
  3880. res = {
  3881. check(...args) {
  3882. _console.log(`${name}.check(`, ...args, ')');
  3883. return new Promise(() => undefined);
  3884. },
  3885. version: "-1"
  3886. };
  3887. if (name === 'advert/adman/adman') {
  3888. let features = {
  3889. siteZones: {},
  3890. slots: {}
  3891. };
  3892. [
  3893. 'expId', 'siteId', 'mimicEndpoint', 'mimicPartnerId',
  3894. 'immediateFetchTimeout', 'delayedFetchTimeout'
  3895. ].forEach(name => void(features[name] = null));
  3896. res = createSkipAllObject(name, {
  3897. getFeatures: skipLog(`${name}.getFeatures`, features)
  3898. });
  3899. }
  3900. if (name === 'mrg-smokescreen/Utils')
  3901. res = createSkipAllObject(name, {
  3902. extend(...args) {
  3903. let res = {
  3904. enable: false,
  3905. match: [],
  3906. links: []
  3907. };
  3908. _console.log(`${name}.extend(`, ...args, ') >>', res);
  3909. return res;
  3910. }
  3911. });
  3912. if (name.startsWith('OK/banners/') ||
  3913. name.startsWith('mrg-smokescreen/StyleSheets') ||
  3914. name === '@mail/mimic' ||
  3915. name === 'mediator/advert-managers')
  3916. res = createSkipAllObject(name);
  3917. if (res) {
  3918. Object.defineProperty(res, Symbol.toStringTag, {
  3919. get() {
  3920. return `Skiplog object for ${name}`;
  3921. }
  3922. });
  3923. Object.defineProperty(res, Symbol.toPrimitive, {
  3924. value(hint) {
  3925. if (hint === 'string')
  3926. return Object.prototype.toString.call(this);
  3927. return `[missing toPrimitive] ${name} ${hint}`;
  3928. }
  3929. });
  3930. res = new Proxy(res, missingCheck);
  3931. } else {
  3932. res = _apply(fun, that, args);
  3933. warn = true;
  3934. }
  3935. _console[warn ? 'warn' : 'log'](name, '(', ...args, ')\n>>', res);
  3936. return res;
  3937. }
  3938. };
  3939.  
  3940. const advModuleNamesStartWith = /^(mrg-(context|honeypot)|adv\/)/;
  3941. const advModuleNamesGeneric = /advert|banner|mimic|smoke/i;
  3942. const wrapAdFuncs = {
  3943. apply(fun, that, args) {
  3944. let module = args[0];
  3945. if (typeof module === 'string')
  3946. if ((advModuleNamesStartWith.test(module) ||
  3947. advModuleNamesGeneric.test(module)) &&
  3948. // fix for e.mail.ru in Fx56 and below, looks like Proxy is quirky there
  3949. !module.startsWith('patron.v2.')) {
  3950. let main = args[args.length - 1];
  3951. main._name = module;
  3952. args[args.length - 1] = new Proxy(main, redefiner);
  3953. }
  3954. return _apply(fun, that, args);
  3955. }
  3956. };
  3957. const wrapDefine = def => {
  3958. if (!def)
  3959. return;
  3960. _console.log('define =', def);
  3961. def = new Proxy(def, wrapAdFuncs);
  3962. def._name = 'define';
  3963. return def;
  3964. };
  3965. let _define = wrapDefine(win.define);
  3966. Object.defineProperty(win, 'define', {
  3967. get() {
  3968. return _define;
  3969. },
  3970. set(x) {
  3971. if (_define === x)
  3972. return true;
  3973. _define = wrapDefine(x);
  3974. return true;
  3975. }
  3976. });
  3977. }
  3978.  
  3979. let _honeyPot;
  3980.  
  3981. function defineDetector(mr) {
  3982. let __ = mr._ || {};
  3983. let setHoneyPot = o => {
  3984. if (!o || o === _honeyPot) return;
  3985. _console.log('[honeyPot]', o);
  3986. _honeyPot = function () {
  3987. this.check = new Proxy(() => {
  3988. __.STUCK_IN_POT = false;
  3989. return false;
  3990. }, logger);
  3991. this.check._name = 'honeyPot.check';
  3992. this.destroy = () => null;
  3993. };
  3994. };
  3995. if ('honeyPot' in mr)
  3996. setHoneyPot(mr.honeyPot);
  3997. else
  3998. Object.defineProperty(mr, 'honeyPot', {
  3999. get() {
  4000. return _honeyPot;
  4001. },
  4002. set: setHoneyPot
  4003. });
  4004.  
  4005. __ = new Proxy(__, {
  4006. get(target, prop) {
  4007. return target[prop];
  4008. },
  4009. set(target, prop, val) {
  4010. _console.log(`mr._.${prop} =`, val);
  4011. target[prop] = val;
  4012. return true;
  4013. }
  4014. });
  4015. mr._ = __;
  4016. }
  4017.  
  4018. function defineAdd(mr) {
  4019. let _add;
  4020. let addWrapper = {
  4021. apply(fun, that, args) {
  4022. let module = args[0];
  4023. if (typeof module === 'string' && module.startsWith('ad')) {
  4024. _console.log('Skip module:', module);
  4025. return;
  4026. }
  4027. if (typeof module === 'object' && module.name.startsWith('ad'))
  4028. _console.log('Loaded module:', module);
  4029. return logger.apply(fun, that, args);
  4030. }
  4031. };
  4032. let setMrAdd = v => {
  4033. if (!v) return;
  4034. v._name = 'mr.add';
  4035. v = new Proxy(v, addWrapper);
  4036. _add = v;
  4037. };
  4038. if ('add' in mr)
  4039. setMrAdd(mr.add);
  4040. Object.defineProperty(mr, 'add', {
  4041. get() {
  4042. return _add;
  4043. },
  4044. set: setMrAdd
  4045. });
  4046.  
  4047. }
  4048.  
  4049. const _mr_wrapper = vl => {
  4050. defineLocator(vl.mimic ? vl.mimic : vl);
  4051. defineDetector(vl);
  4052. defineAdd(vl);
  4053. return vl;
  4054. };
  4055. if ('mr' in win) {
  4056. _console.log('Found existing "mr" object.');
  4057. win.mr = _mr_wrapper(win.mr);
  4058. } else {
  4059. let _mr;
  4060. Object.defineProperty(win, 'mr', {
  4061. get() {
  4062. return _mr;
  4063. },
  4064. set(vl) {
  4065. _mr = vl ? _mr_wrapper(vl) : vl;
  4066. },
  4067. configurable: true
  4068. });
  4069. let _defineProperty = _bindCall(Object.defineProperty);
  4070. Object.defineProperty = function defineProperty(...args) {
  4071. const [obj, name, conf] = args;
  4072. if (name === 'mr' && obj instanceof Window) {
  4073. _console.trace('Object.defineProperty(', ...args, ')');
  4074. conf.set(_mr_wrapper(conf.get()));
  4075. }
  4076. if ((name === 'honeyPot' || name === 'add') && _mr === obj && conf.set)
  4077. return;
  4078. return _defineProperty(this, ...args);
  4079. };
  4080. }
  4081. }, nullTools, selectiveCookies, abortExecution)
  4082. },
  4083.  
  4084. 'oms.matchat.online': () => scriptLander(() => {
  4085. let _rmpGlobals;
  4086. Object.defineProperty(win, 'rmpGlobals', {
  4087. get() {
  4088. return _rmpGlobals;
  4089. },
  4090. set(val) {
  4091. if (val === _rmpGlobals)
  4092. return true;
  4093. _rmpGlobals = new Proxy(val, {
  4094. get(obj, name) {
  4095. if (name === 'adBlockerDetected')
  4096. return false;
  4097. return obj[name];
  4098. },
  4099. set(obj, name, val) {
  4100. if (name === 'adBlockerDetected')
  4101. _console.trace('rmpGlobals.adBlockerDetected =', val);
  4102. else
  4103. obj[name] = val;
  4104. return true;
  4105. }
  4106. });
  4107. }
  4108. });
  4109. }),
  4110.  
  4111. 'megogo.net': {
  4112. now() {
  4113. nt.define('adBlock', false);
  4114. nt.define('showAdBlockMessage', nt.func(null, 'showAdBlockMessage'));
  4115. }
  4116. },
  4117.  
  4118. 'naruto-base.su': () => gardener('div[id^="entryID"],.block', /href="http.*?target="_blank"/i),
  4119.  
  4120. 'otzovik.com': () => scriptLander(() => {
  4121. abortExecution.onGet('Object.prototype.DirectManagerStart');
  4122. abortExecution.onGet('Object.prototype._visibilityConfirmer');
  4123. let _o_math = win.o_math;
  4124. Object.defineProperty(win, 'o_math', {
  4125. get() {
  4126. return _o_math;
  4127. },
  4128. set(val) {
  4129. delete val.ext_uid;
  4130. _o_math = val;
  4131. }
  4132. });
  4133. }, abortExecution, selectiveCookies),
  4134.  
  4135. 'overclockers.ru': {
  4136. now() {
  4137. abortExecution.onAll('cardinals');
  4138. abortExecution.inlineScript('Document.prototype.createElement', {
  4139. pattern: /mamydirect/
  4140. });
  4141. }
  4142. },
  4143.  
  4144. 'peka2.tv': () => {
  4145. let bodyClass = 'body--branding';
  4146. let checkNode = node => {
  4147. for (let className of node.classList)
  4148. if (className.includes('banner') || className === bodyClass) {
  4149. _removeAttribute(node, 'style');
  4150. node.classList.remove(className);
  4151. for (let attr of Array.from(node.attributes))
  4152. if (attr.name.startsWith('advert'))
  4153. _removeAttribute(node, attr.name);
  4154. }
  4155. };
  4156. (new MutationObserver(ms => {
  4157. let m, node;
  4158. for (m of ms)
  4159. for (node of m.addedNodes)
  4160. if (node instanceof HTMLElement)
  4161. checkNode(node);
  4162. })).observe(_de, {
  4163. childList: true,
  4164. subtree: true
  4165. });
  4166. (new MutationObserver(ms => {
  4167. for (let m of ms)
  4168. checkNode(m.target);
  4169. })).observe(_de, {
  4170. attributes: true,
  4171. subtree: true,
  4172. attributeFilter: ['class']
  4173. });
  4174. },
  4175.  
  4176. 'pikabu.ru': () => gardener('.story', /story__author[^>]+>ads</i, {
  4177. root: '.inner_wrap',
  4178. observe: true
  4179. }),
  4180.  
  4181. 'piratbit.tld': {
  4182. other: 'pb.wtf',
  4183. dom() {
  4184. const remove = node => node && node.parentNode && (_console.log('removed', node), node.parentNode.removeChild(node));
  4185. const isAdLink = el => location.hostname === el.hostname && /^\/(\w{3}|exit|out)\/[\w=/]{20,}$/.test(el.pathname);
  4186. // line above topic content and images in the slider in the header
  4187. for (let el of _document.querySelectorAll('.releas-navbar div a, #page_contents a'))
  4188. if (isAdLink(el))
  4189. remove(el.closest('tr[class]:not(.top_line):not(.active), .row2[id^="post_"]') || el.closest('div[style]:not(.row1):not(.btn-group)'));
  4190. }
  4191. },
  4192.  
  4193. 'pixelexperience.org': () => scriptLander(() => {
  4194. abortExecution.inlineScript('eval', {
  4195. pattern: /blockadblock/
  4196. });
  4197. }, abortExecution),
  4198.  
  4199. 'player.starlight.digital': {
  4200. other: 'teleportal.ua',
  4201. dom() {
  4202. scriptLander(() => {
  4203. let _currVideo = win.currVideo;
  4204. Object.defineProperty(win, 'currVideo', {
  4205. get() {
  4206. return _currVideo;
  4207. },
  4208. set(val) {
  4209. _console.log('currVideo =', val);
  4210. if ('adv' in val)
  4211. val.adv.creatives = [];
  4212. if ('showadv' in val)
  4213. val.showadv = false;
  4214. if ('mediaHls' in val)
  4215. val.mediaHls = val.mediaHls.replace('adv=1', 'adv=0');
  4216. if ('media' in val)
  4217. for (let media of val.media)
  4218. media.url = media.url.replace('adv=1', 'adv=0');
  4219. _currVideo = val;
  4220. }
  4221. });
  4222. nt.define('Object.prototype.isAdBlockEnabled', false);
  4223. nt.define('Object.prototype.AdBlockDynamicConfig', undefined);
  4224. nt.define('ADT_PLAYER_ADBLOCK_CONFIG', '');
  4225. nt.define('ADT_PLAYER_ADBLOCK_CONFIG_DETECT_ON_FAIL', false);
  4226. }, nullTools);
  4227. }
  4228. },
  4229.  
  4230. 'qrz.ru': {
  4231. now() {
  4232. nt.define('ab', false);
  4233. nt.define('tryMessage', nt.func(null, 'tryMessage'));
  4234. }
  4235. },
  4236.  
  4237. 'rambler.ru': {
  4238. other: [
  4239. 'autorambler.ru', 'championat.com', 'eda.ru', 'gazeta.ru', 'lenta.ru', 'letidor.ru',
  4240. 'media.eagleplatform.com', 'motor.ru', 'passion.ru', 'quto.ru', 'rns.online', 'wmj.ru'
  4241. ].join(','),
  4242. now() {
  4243. scriptLander(() => {
  4244. // Skip login form and frames, and comments frames. Nothing to do here.
  4245. if (['id.rambler.ru', 'comments.rambler.ru'].includes(location.hostname))
  4246. return;
  4247.  
  4248. // prevent autoplay
  4249. if (location.hostname === 'vp.rambler.ru') {
  4250. nt.define('Object.prototype.VIEWPORT_VISIBLE_AREA_CHANGED', () => false);
  4251. return;
  4252. }
  4253. if (location.hostname.endsWith('.media.eagleplatform.com')) {
  4254. const _stopImmediatePropagation = _bindCall(Event.prototype.stopImmediatePropagation);
  4255. win.addEventListener('message', e => {
  4256. if (typeof e.data === 'object' && e.data.visible)
  4257. _stopImmediatePropagation(e);
  4258. });
  4259. return;
  4260. }
  4261. /* jshint -W001 */ // aka 'hasOwnProperty' is a really bad name, but this is a wrapper
  4262. const autoList = new Set(['autoplay', 'scrollplay']);
  4263. win.Object.prototype.hasOwnProperty = new Proxy(win.Object.prototype.hasOwnProperty, {
  4264. apply(fun, that, args) {
  4265. if (autoList.has(args[0]))
  4266. return false;
  4267. return _apply(fun, that, args);
  4268. }
  4269. });
  4270. /* jshint +W001 */
  4271.  
  4272. selectiveCookies('detect_count|dv|dvr|lv|lvr');
  4273. // Wrapper for adv loader settings in QW50aS1BZEJsb2Nr['7t7hystz']
  4274. const _contexts = new WeakMap();
  4275. Object.defineProperty(Object.prototype, 'Settings', {
  4276. set(val) {
  4277. if (typeof val === 'object' && 'Transports' in val && 'Urls' in val)
  4278. val.Urls = [];
  4279. _contexts.set(this, val);
  4280. },
  4281. get() {
  4282. return _contexts.get(this);
  4283. }
  4284. });
  4285. // disable video pop-outs in articles on gazeta.ru
  4286. if (location.hostname === 'gazeta.ru' || location.hostname.endsWith('.gazeta.ru'))
  4287. nt.define('creepyVideo', nt.func(null, 'creepyVideo'));
  4288. // disable Alice popup (encountered on horoscopes.rambler.ru)
  4289. nt.define('Object.prototype.needShowAlicePopup', false);
  4290. // disable some logging
  4291. yandexRavenStub();
  4292. // hide "disable ads" button
  4293. createStyle('a[href^="https://prime.rambler.ru/promo/"] { display: none !important }');
  4294. // prevent ads from loading
  4295. abortExecution.onGet('g_GazetaNoExchange');
  4296.  
  4297. //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;
  4298. const scriptSkipList = /nrWrapper|\/(desktopVendor|vendorsDesktop)\.|<anonymous>/;
  4299. const isLocalScript = (log) => {
  4300. let e = removeOwnFootprint(new Error()),
  4301. parts = e.stack.split(/\n/),
  4302. row = 0;
  4303. if (!/http/.test(parts[row]))
  4304. row += 1;
  4305. while (scriptSkipList.test(parts[row]))
  4306. row += 1;
  4307. let parse = /(https?:.*):\d+:\d+/.exec(parts[row]);
  4308. if (log)
  4309. _console.log(parse && parse[1] === location.href, parts[row], [parts]);
  4310. return parse && parse[1] === location.href;
  4311. };
  4312. const cutoff = 200;
  4313. const fts = f => _toString(f.__sentry__ && f.__sentry_original__ || f['nr@original'] || f);
  4314. win.setTimeout = new Proxy(win.setTimeout, {
  4315. apply(fun, that, args) {
  4316. if (isLocalScript()) {
  4317. const [callback, delay] = args;
  4318. const str = fts(callback);
  4319. if (!/\n/.test(str)) {
  4320. _console.trace(`Skipped setTimeout(${str.slice(0, cutoff)}${str.length > cutoff ? '\u2026' : ''}, ${delay})`);
  4321. return null;
  4322. }
  4323. }
  4324. return _apply(fun, that, args);
  4325. }
  4326. });
  4327. const _onerror = Object.getOwnPropertyDescriptor(win.HTMLElement.prototype, 'onerror');
  4328. _onerror.set = new Proxy(_onerror.set, {
  4329. apply(fun, that, args) {
  4330. if (typeof args[0] === 'function' && isLocalScript()) {
  4331. const str = fts(args[0]);
  4332. _console.trace(`Skipped onerror = ${str.slice(0, cutoff)}${str.length > cutoff ? '\u2026' : ''}`);
  4333. return;
  4334. }
  4335. return _apply(fun, that, args);
  4336. }
  4337. });
  4338. Object.defineProperty(win.HTMLElement.prototype, 'onerror', _onerror);
  4339. // Skip dev console check
  4340. win.console.debug = new Proxy(win.console.debug, {
  4341. apply(fun, that, args) {
  4342. if (args[0] instanceof HTMLImageElement)
  4343. return;
  4344. return _apply(fun, that, args);
  4345. }
  4346. });
  4347. // anti-abdetector
  4348. let _primeStorage;
  4349. Object.defineProperty(win, 'primeStorage', {
  4350. get() {
  4351. if (isLocalScript())
  4352. throw removeOwnFootprint(new TypeError(`Cannot read property 'primeStorage' of undefined`));
  4353. return _primeStorage;
  4354. },
  4355. set(val) {
  4356. _primeStorage = val;
  4357. }
  4358. });
  4359. // Defense against triggered detector
  4360. _Node.removeChild = new Proxy(_Node.removeChild, {
  4361. apply(fun, that, args) {
  4362. const [el] = args;
  4363. if (el.tagName === 'LINK' && isLocalScript()) {
  4364. _console.log(`Let's not remove ${el.tagName}.`);
  4365. return;
  4366. }
  4367. return _apply(fun, that, args);
  4368. }
  4369. });
  4370. }, nullTools, yandexRavenStub, selectiveCookies, abortExecution);
  4371. },
  4372. dom() {
  4373. // disable video pop-outs in articles on lenta.ru and rambler.ru
  4374. let domain = location.hostname.split('.');
  4375. if (['lenta', 'rambler'].includes(domain[domain.length - 2])) {
  4376. const player = _document.querySelector('.js-video-box__container, .j-mini-player__video');
  4377. if (player) player.removeAttribute('class');
  4378. }
  4379. // remove utm_ form links
  4380. const parser = _document.createElement('a');
  4381. _document.addEventListener('mousedown', (e) => {
  4382. let t = e.target;
  4383. if (!t.href)
  4384. t = t.closest('A');
  4385. if (t && t.href) {
  4386. parser.href = t.href;
  4387. let remove = [];
  4388. let params = parser.search.slice(1).split('&').filter(name => {
  4389. if (name.startsWith('utm_')) {
  4390. remove.push(name);
  4391. return false;
  4392. }
  4393. return true;
  4394. });
  4395. if (remove.length)
  4396. _console.log('Removed parameters from link:', ...remove);
  4397. if (params.length)
  4398. parser.search = `?${params.join('&')}`;
  4399. else
  4400. parser.search = '';
  4401. t.href = parser.href;
  4402. }
  4403. }, false);
  4404. }
  4405. },
  4406.  
  4407. 'razlozhi.ru': {
  4408. now() {
  4409. nt.define('cadb', false);
  4410. for (let func of ['createShadowRoot', 'attachShadow'])
  4411. if (func in _Element)
  4412. _Element[func] = function () {
  4413. return this.cloneNode();
  4414. };
  4415. }
  4416. },
  4417.  
  4418. 'rbc.ru': {
  4419. other: 'autonews.ru, rbcplus.ru, sportrbc.ru',
  4420. now() {
  4421. scriptLander(() => selectiveCookies('adb_on'), selectiveCookies);
  4422. let _RA;
  4423. let setArgs = {
  4424. 'showBanners': true,
  4425. 'showAds': true,
  4426. 'banners.staticPath': '',
  4427. 'paywall.staticPath': '',
  4428. 'banners.dfp.config': [],
  4429. 'banners.dfp.pageTargeting': () => null,
  4430. };
  4431. Object.defineProperty(win, 'RA', {
  4432. get() {
  4433. return _RA;
  4434. },
  4435. set(vl) {
  4436. _console.log('RA =', vl);
  4437. if ('repo' in vl) {
  4438. _console.log('RA.repo =', vl.repo);
  4439. vl.repo = new Proxy(vl.repo, {
  4440. set(obj, name, val) {
  4441. if (name === 'banner') {
  4442. _console.log(`RA.repo.${name} =`, val);
  4443. val = new Proxy(val, {
  4444. get(obj, name) {
  4445. let res = obj[name];
  4446. if (typeof obj[name] === 'function') {
  4447. res = () => undefined;
  4448. if (name === 'getService')
  4449. res = service => {
  4450. if (service === 'dfp')
  4451. return {
  4452. getPlaces() {
  4453. return;
  4454. },
  4455. createPlaceholder() {
  4456. return;
  4457. }
  4458. };
  4459. return undefined;
  4460. };
  4461. res.toString = obj[name].toString.bind(obj[name]);
  4462. }
  4463. if (name === 'isInited')
  4464. res = true;
  4465. _console.trace(`get RA.repo.banner.${name}`, res);
  4466. return res;
  4467. }
  4468. });
  4469. }
  4470. obj[name] = val;
  4471. return true;
  4472. }
  4473. });
  4474. } else
  4475. _console.log('Unable to locate RA.repo');
  4476. _RA = new Proxy(vl, {
  4477. set(o, name, val) {
  4478. if (name === 'config') {
  4479. _console.log('RA.config =', val);
  4480. if ('set' in val) {
  4481. val.set = new Proxy(val.set, {
  4482. apply(set, that, args) {
  4483. let name = args[0];
  4484. if (name in setArgs)
  4485. args[1] = setArgs[name];
  4486. if (name in setArgs || name === 'checkad')
  4487. _console.log('RA.config.set(', ...args, ')');
  4488. return _apply(set, that, args);
  4489. }
  4490. });
  4491. val.set('showAds', true); // pretend ads already were shown
  4492. }
  4493. }
  4494. o[name] = val;
  4495. return true;
  4496. }
  4497. });
  4498. }
  4499. });
  4500. Object.defineProperty(win, 'bannersConfig', {
  4501. set() {},
  4502. get() {
  4503. return [];
  4504. }
  4505. });
  4506. // pretend there is a paywall landing on screen already
  4507. let pwl = _document.createElement('div');
  4508. pwl.style.display = 'none';
  4509. pwl.className = 'js-paywall-landing';
  4510. _document.documentElement.appendChild(pwl);
  4511. // detect and skip execution of one of the ABP detectors
  4512. win.setTimeout = new Proxy(win.setTimeout, {
  4513. apply(fun, that, args) {
  4514. if (typeof args[0] === 'function') {
  4515. let fts = _toString(args[0]);
  4516. if (/\.length\s*>\s*0\s*&&/.test(fts) && /:hidden/.test(fts)) {
  4517. _console.log('Skipped setTimout(', fts, args[1], ')');
  4518. return;
  4519. }
  4520. }
  4521. return _apply(fun, that, args);
  4522. }
  4523. });
  4524. // hide banner placeholders
  4525. createStyle('[data-banner-id], .banner__container, .banners__yandex__article { display: none !important }');
  4526. },
  4527. dom() {
  4528. // hide sticky banner place at the top of the page
  4529. for (let itm of _document.querySelectorAll('.l-sticky'))
  4530. if (itm.querySelector('.banner__container__link'))
  4531. itm.style.display = 'none';
  4532. }
  4533. },
  4534.  
  4535. 'reactor.cc': {
  4536. other: 'joyreactor.cc, pornreactor.cc',
  4537. now: () => scriptLander(() => {
  4538. selectiveEval();
  4539. win.open = function () {
  4540. throw new ReferenceError('Redirect prevention.');
  4541. };
  4542. nt.define('Worker', nt.func(nt.proxy({}, 'Worker'), 'Worker'));
  4543. let _CTRManager = win.CTRManager;
  4544. Object.defineProperty(win, 'CTRManager', {
  4545. get() {
  4546. return _CTRManager;
  4547. },
  4548. set(vl) {
  4549. if (vl === _CTRManager)
  4550. return true;
  4551. _CTRManager = {};
  4552. for (let name in vl)
  4553. if (typeof vl[name] !== 'function')
  4554. _CTRManager[name] = vl[name];
  4555. _CTRManager = nt.proxy(_CTRManager, 'CTRManager');
  4556. }
  4557. });
  4558. }, nullTools, selectiveEval),
  4559. click(e) {
  4560. let node = e.target;
  4561. if (node.nodeType === _Node.ELEMENT_NODE &&
  4562. node.style.position === 'absolute' &&
  4563. node.style.zIndex > 0)
  4564. node.parentNode.removeChild(node);
  4565. }
  4566. },
  4567.  
  4568. 'rp5.tld': {
  4569. now() {
  4570. Object.defineProperty(win, 'sContentBottom', {
  4571. set() {},
  4572. get() {
  4573. return '';
  4574. }
  4575. });
  4576. // skip timeout check for blocked requests
  4577. let _setTimeout = win.setTimeout;
  4578. win.setTimeout = function setTimeout(...args) {
  4579. let str = (typeof args[0] === 'string' ? args[0] : _toString(args[0]));
  4580. if (str.includes('xvb')) {
  4581. _console.log('Blocked setTimeout for:', str);
  4582. return;
  4583. }
  4584. return _setTimeout(...args);
  4585. };
  4586. },
  4587. dom() {
  4588. let node = selectNodeByTextContent('Разместить текстовое объявление', {
  4589. root: _de.querySelector('#content-wrapper'),
  4590. shallow: true
  4591. });
  4592. if (node)
  4593. node.style.display = 'none';
  4594. }
  4595. },
  4596.  
  4597. 'rsload.net': {
  4598. load() {
  4599. let dis = _document.querySelector('label[class*="cb-disable"]');
  4600. if (dis)
  4601. dis.click();
  4602. },
  4603. click(e) {
  4604. let t = e.target;
  4605. if (t && t.href && (/:\/\/\d+\.\d+\.\d+\.\d+\//.test(t.href)))
  4606. t.href = t.href.replace('://', '://rsload.net:rsload.net@');
  4607. }
  4608. },
  4609.  
  4610. 'rustorka.tld': {
  4611. other: [
  4612. 'rustorka.innal.top, rustorka2.innal.top, rustorka3.innal.top',
  4613. 'rustorka4.innal.top, rustorka5.innal.top, rustorka6.innal.top',
  4614. 'rustorka.naylo.top'
  4615. ].join(', '),
  4616. now: () => scriptLander(() => {
  4617. selectiveCookies('~default|(?!(PHPSESSID|__cfduid|announcements|bb_data|bb_t|id|opt_js|shout)$).*');
  4618. selectiveEval(/antiadblock/);
  4619. abortExecution.onGet('ads_script');
  4620. abortExecution.inlineScript('setTimeout', {
  4621. pattern: /("(\\x[0-9A-F]{2})+",\s?){4}/
  4622. });
  4623.  
  4624. const _doc_proto = ('cookie' in _Document) ? _Document : Object.getPrototypeOf(_document);
  4625. const _cookie = Object.getOwnPropertyDescriptor(_doc_proto, 'cookie');
  4626.  
  4627. if (_cookie && GM.info.scriptHandler) {
  4628. const asyncCookieCleaner = () => {
  4629. GM.cookie.list({
  4630. url: location.href
  4631. }).then(cookies => {
  4632. for (let cookie of (cookies || []))
  4633. if (cookie.name === cookie.value) {
  4634. GM.cookie.delete(cookie);
  4635. _console.log(`Removed cookie: ${cookie.name}=${cookie.value}`);
  4636. }
  4637. });
  4638. };
  4639. _cookie.get = new Proxy(_cookie.get, {
  4640. apply(fun, that, args) {
  4641. asyncCookieCleaner();
  4642. return _apply(fun, that, args);
  4643. }
  4644. });
  4645. _cookie.set = new Proxy(_cookie.set, {
  4646. apply(fun, that, args) {
  4647. _apply(fun, that, args);
  4648. asyncCookieCleaner();
  4649. return true;
  4650. }
  4651. });
  4652. Object.defineProperty(_doc_proto, 'cookie', _cookie);
  4653. }
  4654. }, selectiveCookies, abortExecution),
  4655. dom: () => _document.cookie.slice(0, 0)
  4656. },
  4657.  
  4658. 'rutube.ru': () => scriptLander(() => {
  4659. jsonFilter('creative', 'creative.id');
  4660. jsonFilter('interactives', 'interactives.0');
  4661. }, jsonFilter),
  4662.  
  4663. 'sdamgia.ru': () => scriptLander(() => {
  4664. abortExecution.onGet('Object.prototype.getYa');
  4665. abortExecution.onGet('Object.prototype.initYa');
  4666. abortExecution.onGet('Object.prototype.initYaDirect');
  4667. }, abortExecution),
  4668.  
  4669. 'simpsonsua.com.ua': {
  4670. other: 'simpsonsua.tv',
  4671. now: () => scriptLander(() => {
  4672. let _addEventListener = _Document.addEventListener;
  4673. _document.addEventListener = function (event, callback) {
  4674. if (event === 'DOMContentLoaded' && callback.toString().includes('show_warning'))
  4675. return;
  4676. return _addEventListener.apply(this, arguments);
  4677. };
  4678. nt.define('need_warning', 0);
  4679. nt.define('onYouTubeIframeAPIReady', nt.func(null, 'onYouTubeIframeAPIReady'));
  4680. }, nullTools)
  4681. },
  4682.  
  4683. 'smotret-anime-365.ru': () => scriptLander(() => {
  4684. deepWrapAPI(root => {
  4685. const _pause = _bindCall(root.Audio.prototype.pause);
  4686. const _addEventListener = _bindCall(root.Element.prototype.addEventListener);
  4687. let stopper = e => _pause(e.target);
  4688. root.Audio = new Proxy(root.Audio, {
  4689. construct(audio, args) {
  4690. let res = _construct(audio, args);
  4691. _addEventListener(res, 'play', stopper, true);
  4692. return res;
  4693. }
  4694. });
  4695. let _tagName_get = _bindCall(Object.getOwnPropertyDescriptor(_Element, 'tagName').get);
  4696. root.Document.prototype.createElement = new Proxy(root.Document.prototype.createElement, {
  4697. apply(fun, that, args) {
  4698. let res = _apply(fun, that, args);
  4699. if (_tagName_get(res) === 'AUDIO')
  4700. _addEventListener(res, 'play', stopper, true);
  4701. return res;
  4702. }
  4703. });
  4704. });
  4705. }, deepWrapAPI),
  4706.  
  4707. 'spaces.ru': () => {
  4708. gardener('div:not(.f-c_fll) > a[href*="spaces.ru/?Cl="]', /./, {
  4709. parent: 'div'
  4710. });
  4711. gardener('.js-banner_rotator', /./, {
  4712. parent: '.widgets-group'
  4713. });
  4714. },
  4715.  
  4716. 'spam-club.blogspot.co.uk': () => {
  4717. let _clientHeight = Object.getOwnPropertyDescriptor(_Element, 'clientHeight'),
  4718. _clientWidth = Object.getOwnPropertyDescriptor(_Element, 'clientWidth');
  4719. let wrapGetter = (getter) => {
  4720. let _getter = getter;
  4721. return function () {
  4722. let _size = _getter.apply(this, arguments);
  4723. return _size ? _size : 1;
  4724. };
  4725. };
  4726. _clientHeight.get = wrapGetter(_clientHeight.get);
  4727. _clientWidth.get = wrapGetter(_clientWidth.get);
  4728. Object.defineProperty(_Element, 'clientHeight', _clientHeight);
  4729. Object.defineProperty(_Element, 'clientWidth', _clientWidth);
  4730. let _onload = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onload'),
  4731. _set_onload = _onload.set;
  4732. _onload.set = function () {
  4733. if (this instanceof HTMLImageElement)
  4734. return true;
  4735. _set_onload.apply(this, arguments);
  4736. };
  4737. Object.defineProperty(HTMLElement.prototype, 'onload', _onload);
  4738. },
  4739.  
  4740. 'sport-express.ru': () => gardener('.js-relap__item', />Реклама\s+<\//, {
  4741. root: '.container',
  4742. observe: true
  4743. }),
  4744.  
  4745. 'sports.ru': {
  4746. other: 'tribuna.com',
  4747. now() {
  4748. // extra functionality: shows/hides panel at the top depending on scroll direction
  4749. createStyle({
  4750. '.user-panel__fixed': {
  4751. transition: 'top 0.2s ease-in-out!important'
  4752. },
  4753. '.popup__overlay.feedback': {
  4754. display: 'none!important'
  4755. },
  4756. '.user-panel-up': {
  4757. top: '-40px!important'
  4758. },
  4759. '#branding-layout': {
  4760. margin_top: '100px!important'
  4761. }
  4762. }, {
  4763. id: 'fixes',
  4764. protect: false
  4765. });
  4766. scriptLander(() => {
  4767. yandexRavenStub();
  4768. webpackJsonpFilter(/AdBlockDetector|addBranding|loadPlista/);
  4769. }, nullTools, yandexRavenStub, webpackJsonpFilter);
  4770. },
  4771. dom() {
  4772. (function lookForPanel() {
  4773. let panel = _document.querySelector('.user-panel__fixed');
  4774. if (!panel)
  4775. setTimeout(lookForPanel, 100);
  4776. else
  4777. window.addEventListener(
  4778. 'wheel',
  4779. function (e) {
  4780. if (e.deltaY > 0 && !panel.classList.contains('user-panel-up'))
  4781. panel.classList.add('user-panel-up');
  4782. else if (e.deltaY < 0 && panel.classList.contains('user-panel-up'))
  4783. panel.classList.remove('user-panel-up');
  4784. }, false
  4785. );
  4786. })();
  4787. }
  4788. },
  4789.  
  4790. 'stealthz.ru': {
  4791. dom() {
  4792. // skip timeout
  4793. let $ = _document.querySelector.bind(_document);
  4794. let [timer_1, timer_2] = [$('#timer_1'), $('#timer_2')];
  4795. if (!timer_1 || !timer_2)
  4796. return;
  4797. timer_1.style.display = 'none';
  4798. timer_2.style.display = 'block';
  4799. }
  4800. },
  4801.  
  4802. 'tortuga.wtf': () => {
  4803. nt.define('Object.prototype.hideab', undefined);
  4804. },
  4805.  
  4806. 'tv.animebest.org': {
  4807. now() {
  4808. let _eval = win.eval;
  4809. win.eval = new win.Proxy(win.eval, {
  4810. apply(evl, ths, args) {
  4811. if (typeof args[0] === 'string' &&
  4812. args[0].includes("'VASTP'")) {
  4813. args[0] = args[0].replace("'VASTP'", "''");
  4814. win.eval = _eval;
  4815. }
  4816. return Reflect.apply(evl, ths, args);
  4817. }
  4818. });
  4819. }
  4820. },
  4821.  
  4822. 'tv-kanali.online': () => {
  4823. win.setTimeout = new Proxy(win.setTimeout, {
  4824. apply(fun, that, args) {
  4825. if (args[0].name && args[0].name.includes('doAd'))
  4826. return;
  4827. if (args[1] === 30000) args[1] = 100;
  4828. return _apply(fun, that, args);
  4829. }
  4830. });
  4831. },
  4832.  
  4833. 'video.khl.ru': () => {
  4834. let props = new Set(['detectBlockers', 'detectBlockersByLink', 'detectBlockersByElement']);
  4835. win.Object.defineProperty = new Proxy(win.Object.defineProperty, {
  4836. apply(def, that, args) {
  4837. if (props.has(args[1])) {
  4838. args[2] = {
  4839. key: args[1],
  4840. value() {
  4841. _console.log(`Skipped ${args[1]} call.`);
  4842. }
  4843. };
  4844. _console.log(`Replaced method ${args[1]}.`);
  4845. }
  4846. return Reflect.apply(def, that, args);
  4847. }
  4848. });
  4849. },
  4850.  
  4851. 'xatab-repack.net': {
  4852. other: 'rg-mechanics.org',
  4853. now() {
  4854. abortExecution.onSet('blocked');
  4855. }
  4856. },
  4857.  
  4858. 'xittv.net': () => scriptLander(() => {
  4859. let logNames = ['setup', 'trigger', 'on', 'off', 'onReady', 'onError', 'getConfig', 'addPlugin', 'getAdBlock'];
  4860. let skipEvents = ['adComplete', 'adSkipped', 'adBlock', 'adRequest', 'adMeta', 'adImpression', 'adError', 'adTime', 'adStarted', 'adClick'];
  4861. let _jwplayer;
  4862. Object.defineProperty(win, 'jwplayer', {
  4863. get() {
  4864. return _jwplayer;
  4865. },
  4866. set(x) {
  4867. _jwplayer = new Proxy(x, {
  4868. apply(fun, that, args) {
  4869. let res = fun.apply(that, args);
  4870. res = new Proxy(res, {
  4871. get(obj, name) {
  4872. if (logNames.includes(name) && typeof obj[name] === 'function')
  4873. return new Proxy(obj[name], {
  4874. apply(fun, that, args) {
  4875. if (name === 'setup') {
  4876. let o = args[0];
  4877. if (o)
  4878. delete o.advertising;
  4879. }
  4880. if (name === 'on' || name === 'trigger') {
  4881. let events = typeof args[0] === 'string' ? args[0].split(" ") : null;
  4882. if (events.length === 1 && skipEvents.includes(events[0]))
  4883. return res;
  4884. if (events.length > 1) {
  4885. let names = [];
  4886. for (let event of events)
  4887. if (!skipEvents.includes(event))
  4888. names.push(event);
  4889. if (names.length > 0)
  4890. args[0] = names.join(" ");
  4891. else
  4892. return res;
  4893. }
  4894. }
  4895. let subres = fun.apply(that, args);
  4896. _console.trace(`jwplayer().${name}(`, ...args, `) >>`, res);
  4897. return subres;
  4898. }
  4899. });
  4900. return obj[name];
  4901. }
  4902. });
  4903. return res;
  4904. }
  4905. });
  4906. _console.log('jwplayer =', x);
  4907. }
  4908. });
  4909. }),
  4910.  
  4911. 'yandex.tld': {
  4912. other: 'yandexsport.tld',
  4913. now: () => {
  4914. // Generic Yandex Scripts
  4915. const mainScript = () => {
  4916. let nt = new nullTools({
  4917. log: false,
  4918. trace: true
  4919. });
  4920.  
  4921. let cookiefilter = '';
  4922. // ads on afisha.yandex.ru, however it looks like selectiveEval isn't perfect
  4923. // since eval could be called in scope to access properties of that scope and
  4924. // such calls with it active break functionality on metrika.yandex.ru
  4925. if (/(^|\.)afisha\./.test(location.hostname)) {
  4926. selectiveEval(/AdvManagerStatic/);
  4927. nt.define('Object.prototype._adbStyles', null);
  4928. nt.define('Object.prototype._adbClass', null);
  4929. cookiefilter += (cookiefilter.length ? '|' : '') + 'checkcookie';
  4930. }
  4931.  
  4932. selectiveCookies(cookiefilter);
  4933. // remove banner on the start page
  4934. let AwapsJsonAPI_Json = function (...args) {
  4935. _console.log('>> new AwapsJsonAPI.Json(', ...args, ')');
  4936. };
  4937. const cleaner = (_params, nodes) => {
  4938. try {
  4939. for (let i = 0; i < nodes.length; i++)
  4940. nodes[i].parentNode.parentNode.removeChild(nodes[i].parentNode);
  4941. _console.log(`Removed banner placeholder.`);
  4942. } catch (ignore) {
  4943. _console.log(`Can't locate placeholder to remove.`);
  4944. }
  4945. };
  4946. Object.assign(AwapsJsonAPI_Json.prototype, {
  4947. checkBannerVisibility: nt.func(true, 'AwapsJsonAPI.Json.checkBannerVisibility'),
  4948. autorefresh: nt.proxy(cleaner, 'AwapsJsonAPI.Json.prototype.autorefresh'),
  4949. addIframeContent: nt.proxy(cleaner, 'AwapsJsonAPI.Json.prototype.addIframeContent'),
  4950. getHTML: nt.func('', 'AwapsJsonAPI.Json.getHTML')
  4951. });
  4952. AwapsJsonAPI_Json.prototype = nt.proxy(AwapsJsonAPI_Json.prototype, 'AwapsJsonAPI.Json.prototype');
  4953. AwapsJsonAPI_Json = nt.proxy(AwapsJsonAPI_Json);
  4954. if ('AwapsJsonAPI' in win) {
  4955. _console.log('Oops! AwapsJsonAPI already defined.');
  4956. let f = win.AwapsJsonAPI.Json;
  4957. win.AwapsJsonAPI.Json = AwapsJsonAPI_Json;
  4958. if (f && f.prototype)
  4959. f.prototype = AwapsJsonAPI_Json.prototype;
  4960. } else
  4961. nt.define('AwapsJsonAPI', nt.proxy({
  4962. Json: AwapsJsonAPI_Json
  4963. }));
  4964.  
  4965. let parseExport = x => {
  4966. if (!x)
  4967. return x;
  4968. // remove banner placeholder
  4969. if (x.banner && x.banner.cls && x.banner.cls.banner__parent) {
  4970. let hide = pattern => {
  4971. for (let banner of _document.querySelectorAll(pattern)) {
  4972. _setAttribute(banner, 'style', 'display:none!important');
  4973. _console.log('Hid banner placeholder.');
  4974. }
  4975. };
  4976. let _parent = `.${x.banner.cls.banner__parent}`;
  4977. hide(_parent);
  4978. _document.addEventListener('DOMContentLoaded', () => hide(_parent), false);
  4979. }
  4980.  
  4981. // remove banner data and some other stuff
  4982. delete x.banner;
  4983. delete x.consistency;
  4984. delete x['i-bannerid'];
  4985. delete x['i-counter'];
  4986. delete x['promo-curtain'];
  4987.  
  4988. // remove parts of ga-counter (complete removal break "ТВ Онлайн")
  4989. if (x['ga-counter'] && x['ga-counter'].data) {
  4990. x['ga-counter'].data.id = 0;
  4991. delete x['ga-counter'].data.ether;
  4992. delete x['ga-counter'].data.iframeSrc;
  4993. delete x['ga-counter'].data.iframeSrcEx;
  4994. }
  4995.  
  4996. // remove adblock detector parameters and clean up detector cookie
  4997. if ('adb' in x) {
  4998. let cookie = x.adb.data ? x.adb.data.cookie : undefined;
  4999. if (cookie) {
  5000. selectiveCookies(cookie);
  5001. x.adb.data.adb = 0;
  5002. }
  5003. delete x.adb;
  5004. }
  5005.  
  5006. return x;
  5007. };
  5008. // Yandex banner on main page and some other things
  5009. let _home = win.home,
  5010. _home_set = !!_home;
  5011. Object.defineProperty(win, 'home', {
  5012. get() {
  5013. return _home;
  5014. },
  5015. set(vl) {
  5016. if (!_home_set && vl === _home)
  5017. return;
  5018. _home_set = false;
  5019. _console.log('home =', vl);
  5020. let _home_export = parseExport(vl.export);
  5021. Object.defineProperty(vl, 'export', {
  5022. get() {
  5023. return _home_export;
  5024. },
  5025. set(vl) {
  5026. _home_export = parseExport(vl);
  5027. }
  5028. });
  5029. _home = vl;
  5030. }
  5031. });
  5032.  
  5033. // adblock circumvention on some Yandex domains
  5034. yandexRavenStub();
  5035.  
  5036. // news, sport, docviewer in emails and probably other places
  5037. abortExecution.onGet('yaads.adRenderedCount');
  5038. let AdvertPartner = nt.func(false, 'AdvertPartner');
  5039. nt.defineOn(AdvertPartner, 'defaultProps', {}, 'AdvertPartner.');
  5040. nt.defineOn(AdvertPartner, 'contextTypes', [], 'AdvertPartner.');
  5041. nt.define('Object.prototype.AdvertPartner', AdvertPartner);
  5042. // ads in videoplayer
  5043. nt.define('Object.prototype.useAbdBundle', false);
  5044.  
  5045. (path => { // code specific for certain paths on yandex
  5046. const paths = {
  5047. news: () => {
  5048. createStyle(
  5049. 'div[class]:not(.mg-grid__col) > .mg-grid__row > .mg-grid__col:last-child,' +
  5050. '.news-top-rubric-heading > span:only-child { display: none !important }'
  5051. );
  5052. gardener('.mg-grid__col > div[class*="_type_"]', /./, {
  5053. root: '.news-app__feed',
  5054. parent: '.mg-grid__col',
  5055. observe: true,
  5056. hide: true
  5057. });
  5058. },
  5059. sport: () => createStyle('.sport-advert_type_card { display: none !important }'),
  5060. pogoda: () => createStyle(
  5061. 'div[class^="content "][data-bem] > .content__bottom ~ div[class^="card "],' +
  5062. '[class$="segment__container"] > div > [class^="card "][class*="_"],' +
  5063. '.b-statcounter + div[class] > div[id][class] { display: none !important }'
  5064. )
  5065. };
  5066. if (paths[path]) paths[path]();
  5067. })(location.pathname.slice(1, (x => x < 0 ? undefined : x)(location.pathname.indexOf('/', 1))).toLowerCase());
  5068.  
  5069. // abp detector cookie on yandex pogoda and afisha
  5070. win.Element.prototype.getAttribute = new Proxy(win.Element.prototype.getAttribute, {
  5071. apply(get, el, args) {
  5072. let res = _apply(get, el, args);
  5073. if (res && res.length > 20 && el instanceof HTMLBodyElement)
  5074. try {
  5075. let o = JSON.parse(res),
  5076. found = false,
  5077. check;
  5078. for (let prop in o) {
  5079. check = 'param' in o[prop] || 'aabCookieName' in o[prop];
  5080. if (check || 'banners' in o[prop]) {
  5081. found = true;
  5082. if (check)
  5083. selectiveCookies(o[prop].param || o[prop].aabCookieName);
  5084. _console.log(el.tagName, o, 'removed', o[prop]);
  5085. delete o[prop];
  5086. }
  5087. }
  5088. if (!found) _console.log(el.tagName, o);
  5089. res = JSON.stringify(o);
  5090. } catch (ignore) {}
  5091. return res;
  5092. }
  5093. });
  5094. };
  5095. scriptLander(mainScript, nullTools, yandexRavenStub, abortExecution, selectiveCookies, selectiveEval);
  5096.  
  5097. if ('attachShadow' in _Element) try {
  5098. let fakeRoot = () => ({
  5099. firstChild: null,
  5100. appendChild() {
  5101. return null;
  5102. },
  5103. querySelector() {
  5104. return null;
  5105. },
  5106. querySelectorAll() {
  5107. return null;
  5108. }
  5109. });
  5110. _Element.createShadowRoot = fakeRoot;
  5111. let shadows = new WeakMap();
  5112. let _attachShadow = Object.getOwnPropertyDescriptor(_Element, 'attachShadow');
  5113. _attachShadow.value = function () {
  5114. return shadows.set(this, fakeRoot()).get(this);
  5115. };
  5116. Object.defineProperty(_Element, 'attachShadow', _attachShadow);
  5117. let _shadowRoot = Object.getOwnPropertyDescriptor(_Element, 'shadowRoot');
  5118. _shadowRoot.set = () => null;
  5119. _shadowRoot.get = function () {
  5120. return shadows.has(this) ? shadows.get(this) : undefined;
  5121. };
  5122. Object.defineProperty(_Element, 'shadowRoot', _shadowRoot);
  5123. } catch (e) {
  5124. _console.warn('Unable to wrap Element.prototype.attachShadow\n', e);
  5125. }
  5126.  
  5127. // Disable banner styleSheet (on main page)
  5128. document.addEventListener('DOMContentLoaded', () => {
  5129. for (let sheet of document.styleSheets)
  5130. try {
  5131. for (let rule of sheet.cssRules)
  5132. if (rule.cssText.includes(' 728px 90px')) {
  5133. rule.parentStyleSheet.disabled = true;
  5134. _console.log('Disabled banner styleSheet:', rule.parentStyleSheet);
  5135. }
  5136. } catch (ignore) {}
  5137. }, false);
  5138.  
  5139. // Subdomain-specific Yandex scripts
  5140. const subDomain = location.hostname.slice(0, location.hostname.indexOf('.'));
  5141.  
  5142. // Yandex Mail ads
  5143. if (subDomain === 'mail') {
  5144. let wrap = vl => {
  5145. if (!vl)
  5146. return vl;
  5147. _console.log('Daria =', vl);
  5148. nt.defineOn(vl, 'AdBlock', nt.proxy({
  5149. detect: nt.func(new Promise(() => null), 'Daria.AdBlock.detect'),
  5150. enabled: false
  5151. }), 'Daria.');
  5152. nt.defineOn(vl, 'AdvPresenter', nt.proxy({
  5153. _config: nt.proxy({
  5154. banner: false,
  5155. done: false,
  5156. line: false
  5157. })
  5158. }), 'Daria.');
  5159. if (vl.Config) {
  5160. delete vl.Config.adBlockDetector;
  5161. delete vl.Config['adv-url'];
  5162. delete vl.Config.cryprox;
  5163. if (vl.Config.features) {
  5164. delete vl.Config.features.web_adloader_with_cookie_cache;
  5165. delete vl.Config.features.web_ads;
  5166. delete vl.Config.features.web_ads_mute;
  5167. }
  5168. vl.Config.mayHaveAdv = false;
  5169. }
  5170. return vl;
  5171. };
  5172. let _Daria = wrap(win.Daria);
  5173. if (_Daria)
  5174. _console.log('Wrapped already existing object "Daria".');
  5175. Object.defineProperty(win, 'Daria', {
  5176. get() {
  5177. return _Daria;
  5178. },
  5179. set(vl) {
  5180. if (vl === _Daria)
  5181. return;
  5182. _Daria = wrap(vl);
  5183. }
  5184. });
  5185. }
  5186.  
  5187. // Detector and ads on Yandex Music
  5188. if (subDomain === 'music') {
  5189. nt.define('tryPay', nt.func(null, 'tryPay'));
  5190. nt.define('Object.prototype.initMegabannerAPI', nt.func(null, 'initMegabannerAPI'));
  5191. nt.define('Object.prototype.mediaAd', undefined);
  5192. nt.define('Object.prototype.detect', () => new Promise(() => null));
  5193. nt.define('Object.prototype.loadContext', () => new Promise(r => r()));
  5194. nt.define('Object.prototype.antiAdbSetup', nt.func(null, 'ya.music.antiAdbSetup'));
  5195. }
  5196.  
  5197. const isSearch = /^\/(yand)?search[/?]/i.test(location.pathname);
  5198. if (['mail', 'music', 'tv', 'yandexsport'].includes(subDomain) || isSearch) {
  5199. // prevent/defuse adblock detector and cleanup localStorage
  5200. for (let name in localStorage)
  5201. if (name.startsWith('videoplayer-ad-session-') || ['ic', 'yu', 'ludca', 'test'].includes(name))
  5202. localStorage.removeItem(name);
  5203. nt.define('localStorage._mt__data', '');
  5204. nt.define('localStorage.yandexJSPlayerApiSavedSingleVideoSessionWatchedTimeSinceAd', Math.random() * 1000);
  5205.  
  5206. // cookie cleaner
  5207. let yp_keepCookieParts = /\.(sp|ygo|ygu)\./; // ygo = city id; ygu = detect city automatically
  5208. let _doc_proto = ('cookie' in _Document) ? _Document : Object.getPrototypeOf(_document);
  5209. let _cookie = Object.getOwnPropertyDescriptor(_doc_proto, 'cookie');
  5210. if (_cookie) {
  5211. let _set_cookie = _bindCall(_cookie.set);
  5212. _cookie.set = function (value) {
  5213. if (/^(mda=|yp=|ys=|yabs-|__|bltsr=)/.test(value))
  5214. // remove value, set expired
  5215. if (!value.startsWith('yp=')) {
  5216. value = value.replace(/^([^=]+=)[^;]+/, '$1').replace(/(expires=)[\w\s\d,]+/, '$1Thu, 01 Jan 1970 00');
  5217. _console.trace('expire cookie', value.match(/^[^=]+/)[0]);
  5218. } else {
  5219. let parts = value.split(';');
  5220. let values = parts[0].split('#').filter(part => yp_keepCookieParts.test(part));
  5221. if (values.length)
  5222. values[0] = values[0].replace(/^yp=/, '');
  5223. let res = `yp=${values.join('#')}`;
  5224. _console.trace(`set cookie ${res}, dropped ${parts[0].replace(res,'')}`);
  5225. parts[0] = res;
  5226. value = parts.join(';');
  5227. }
  5228. return _set_cookie(this, value);
  5229. };
  5230. Object.defineProperty(_doc_proto, 'cookie', _cookie);
  5231. }
  5232. }
  5233. },
  5234. dom: () => {
  5235. { // Partially based on https://greasyfork.org/en/scripts/22737-remove-yandex-redirect
  5236. let count = 0,
  5237. lock = false;
  5238. const log = () => {
  5239. count++;
  5240. if (lock)
  5241. return;
  5242. setTimeout(() => {
  5243. _console.log('Removed tracking attributes from', count, 'links.');
  5244. count = 0;
  5245. lock = false;
  5246. }, 3333);
  5247. lock = true;
  5248. };
  5249. const selectors = (
  5250. 'A[onmousedown*="/jsredir"],' +
  5251. 'A[data-log-node],' +
  5252. 'A[data-vdir-href],' +
  5253. 'A[data-counter]'
  5254. );
  5255. const removeTrackingAttributes = (link) => {
  5256. _removeAttribute(link, 'onmousedown');
  5257. _removeAttribute(link, 'data-log-node');
  5258. // data-vdir-href
  5259. _removeAttribute(link, 'data-vdir-href');
  5260. _removeAttribute(link, 'data-orig-href');
  5261. // data-counter
  5262. _removeAttribute(link, 'data-counter');
  5263. _removeAttribute(link, 'data-bem');
  5264. log();
  5265. };
  5266. const removeTracking = (scope) => {
  5267. if (scope instanceof Element)
  5268. for (let link of scope.querySelectorAll(selectors))
  5269. removeTrackingAttributes(link);
  5270. };
  5271.  
  5272. removeTracking(_document);
  5273. (new MutationObserver(
  5274. function (ms) {
  5275. let m, node;
  5276. for (m of ms)
  5277. for (node of m.addedNodes)
  5278. if (node instanceof HTMLAnchorElement && node.matches(selectors))
  5279. removeTrackingAttributes(node);
  5280. else
  5281. removeTracking(node);
  5282. }
  5283. )).observe(_de, {
  5284. childList: true,
  5285. subtree: true
  5286. });
  5287. }
  5288.  
  5289. // Subdomain-specific Yandex scripts
  5290. const subDomain = location.hostname.slice(0, location.hostname.indexOf('.'));
  5291.  
  5292. // Function to attach an observer to monitor dynamic changes on the page
  5293. const pageUpdateObserver = (func, obj, params) => {
  5294. if (obj)
  5295. (new MutationObserver(func))
  5296. .observe(obj, (params || {
  5297. childList: true,
  5298. subtree: true
  5299. }));
  5300. };
  5301. // Short name for parentNode.removeChild
  5302. const remove = node => {
  5303. if (!node || !node.parentNode)
  5304. return false;
  5305. _console.log('Removed node.');
  5306. node.parentNode.removeChild(node);
  5307. };
  5308. // Short name for setAttribute style to display:none
  5309. const hide = node => {
  5310. if (!node)
  5311. return false;
  5312. _console.log('Hid node.');
  5313. _setAttribute(node, 'style', 'display:none!important');
  5314. };
  5315.  
  5316. if (subDomain === 'music') {
  5317. const removeMusicAds = () => {
  5318. for (let node of _querySelectorAll('.ads-block'))
  5319. remove(node);
  5320. };
  5321. pageUpdateObserver(removeMusicAds, _querySelector('.sidebar'));
  5322. removeMusicAds();
  5323. }
  5324.  
  5325. if (subDomain === 'tv') {
  5326. const removeTVAds = () => {
  5327. const yadWord = /Яндекс.Директ/i;
  5328. for (let node of _querySelectorAll('div[class^="_"][data-reactid] > div'))
  5329. if (yadWord.test(node.textContent) || node.querySelector('iframe:not([src])')) {
  5330. if (node.offsetWidth) {
  5331. let pad = _document.createElement('div');
  5332. _setAttribute(pad, 'style', `width:${node.offsetWidth}px`);
  5333. node.parentNode.appendChild(pad);
  5334. }
  5335. remove(node);
  5336. }
  5337. };
  5338. pageUpdateObserver(removeTVAds, _document.body);
  5339. removeTVAds();
  5340. }
  5341.  
  5342. const isSearch = /^\/(yand)?search[/?]/i.test(location.pathname);
  5343. if (isSearch) {
  5344. const removeSearchAds = () => {
  5345. const adWords = /Реклама|Ad/i;
  5346. for (let node of _querySelectorAll('.serp-item'))
  5347. if (_getAttribute(node, 'role') === 'complementary' ||
  5348. adWords.test((node.querySelector('.label') || {}).textContent))
  5349. hide(node);
  5350. };
  5351. pageUpdateObserver(removeSearchAds, _querySelector('.main__content'));
  5352. removeSearchAds();
  5353. }
  5354.  
  5355. if (['mail', 'music', 'tv', 'yandexsport'].includes(subDomain) || isSearch) {
  5356. // Generic ads removal and fixes
  5357. for (let node of _querySelectorAll('.serp-header'))
  5358. node.style.marginTop = '0';
  5359. for (let node of _querySelectorAll(
  5360. '.serp-adv__head + .serp-item,' +
  5361. '#adbanner,' +
  5362. '.serp-adv,' +
  5363. '.b-spec-adv,' +
  5364. 'div[class*="serp-adv__"]:not(.serp-adv__found):not(.serp-adv__displayed)'
  5365. )) remove(node);
  5366. }
  5367. }
  5368. },
  5369.  
  5370. 'yap.ru': {
  5371. other: 'yaplakal.com',
  5372. now() {
  5373. gardener('form > table[id^="p_row_"]:nth-of-type(2)', /member1438|Administration/);
  5374. gardener('.icon-comments', /member1438|Administration|\/go\/\?http/, {
  5375. parent: 'tr',
  5376. siblings: -2
  5377. });
  5378. }
  5379. },
  5380.  
  5381. 'yapx.ru': () => scriptLander(() => {
  5382. selectiveCookies('adblock_state|adblock_views');
  5383. nt.define('blockAdBlock', {
  5384. on: nt.func(nt.proxy({}, 'blockAdBlock.on', nt.NULL), 'blockAdBlock.on'),
  5385. check: nt.func(null, 'blockAdBlock.check')
  5386. });
  5387. }, selectiveCookies, nullTools),
  5388.  
  5389. 'youtube.com': () => scriptLander(() => {
  5390. jsonFilter('playerResponse.adPlacements playerResponse.playerAds adPlacements playerAds');
  5391. }, jsonFilter),
  5392.  
  5393. 'znanija.com': () => scriptLander(() => {
  5394. localStorage.clear();
  5395. }, abortExecution)
  5396. };
  5397.  
  5398. // replace '.tld' in domain names, add alternative domain names if present and wrap functions into objects
  5399. {
  5400. const parts = _document.domain.split('.');
  5401. const tld = /\.tld$/;
  5402. const tldSubstitur = (() => {
  5403. // stores TLD of current domain (simplistic TLD implementation)
  5404. const last = parts.length - 1;
  5405. const tld = ['', parts[last]];
  5406. const secondLevel = [
  5407. 'biz', 'com', 'edu', 'gov', 'info', 'int', 'mil', 'net', 'org', 'pro'
  5408. ];
  5409. // add second from the end part of domain name as part of the TLD substitutor
  5410. // when domain name consists of more than 2 parts and it looks like a part of TLD
  5411. if ((parts[0] !== 'www' && parts.length > 2 || parts.length > 3) &&
  5412. (parts[last - 1].length < 3 || secondLevel.includes(parts[last - 1])))
  5413. tld.splice(0, 1, parts[last - 1]);
  5414. return tld.join('.');
  5415. })();
  5416. for (let name in scripts) {
  5417. if (typeof scripts[name] === 'function')
  5418. scripts[name] = {
  5419. now: scripts[name]
  5420. };
  5421. if (name.endsWith('.tld'))
  5422. scripts[name.replace(tld, tldSubstitur)] = scripts[name];
  5423. for (let domain of (scripts[name].other && scripts[name].other.split(/,\s*/) || [])) {
  5424. domain = domain.replace(tld, tldSubstitur);
  5425. if (domain in scripts)
  5426. _console.log('Error in scripts list. Script for', name, 'replaced script for', domain);
  5427. scripts[domain] = scripts[name];
  5428. }
  5429. delete scripts[name].other;
  5430. }
  5431. // scripts lookup
  5432. const windowEvents = ['load', 'unload', 'beforeunload'];
  5433. let domain;
  5434. while (parts.length > 1) {
  5435. domain = parts.join('.');
  5436. if (domain in scripts) {
  5437. for (let when in scripts[domain]) {
  5438. let script = scripts[domain][when];
  5439. if (when === 'now')
  5440. script();
  5441. else if (when === 'dom')
  5442. _document.addEventListener('DOMContentLoaded', script);
  5443. else if (windowEvents.includes(when))
  5444. win.addEventListener(when, scripts[domain][when]);
  5445. else
  5446. _document.addEventListener(when, scripts[domain][when]);
  5447. }
  5448. }
  5449. parts.shift();
  5450. }
  5451. }
  5452.  
  5453. // Batch script lander
  5454. if (!skipLander)
  5455. landScript(batchLand, batchPrepend);
  5456.  
  5457. { // JS Fixes Tools Menu
  5458. const incompatibleScriptHandler = !/^(Tamper|Violent)monkey$/.test(GM.info.scriptHandler) || GM.info.scriptHandler === 'Violentmonkey' && isFirefox;
  5459. // Debug function, lists all unusual window properties
  5460. const isNativeFunction = /^[^{]*\{[\s\r\n]*\[native\scode\][\s\r\n]*\}$/;
  5461. const getStrangeObjectsList = () => {
  5462. _console.group('Window strangers list');
  5463. const _skip = 'frames/self/window/webkitStorageInfo'.split('/');
  5464. for (let n of Object.getOwnPropertyNames(win))
  5465. try {
  5466. let val = win[n];
  5467. if (val && !_skip.includes(n) && (win !== window && val !== window[n] || win === window) &&
  5468. (typeof val !== 'function' || typeof val === 'function' && !isNativeFunction.test(_toString(val))))
  5469. _console.log(`${n} =`, val);
  5470. } catch (e) {
  5471. _console.log(n, 'returns error on read', e);
  5472. }
  5473. _console.groupEnd('Window strangers list');
  5474. };
  5475.  
  5476. const lines = {
  5477. linked: [],
  5478. MenuOptions: {
  5479. eng: 'Options',
  5480. rus: 'Настройки'
  5481. },
  5482. MenuCompatibilityWarning: {
  5483. eng: 'is not supported',
  5484. rus: 'не поддерживается'
  5485. },
  5486. langs: {
  5487. eng: 'English',
  5488. rus: 'Русский'
  5489. },
  5490. sObjBtn: {
  5491. eng: 'List unusual "window" properties in console',
  5492. rus: 'Вывести в консоль нестандартные свойства «window»'
  5493. },
  5494. HeaderTools: {
  5495. eng: 'Tools',
  5496. rus: 'Инструменты'
  5497. },
  5498. HeaderOptions: {
  5499. eng: 'Options',
  5500. rus: 'Настройки'
  5501. },
  5502. AccessStatisticsLabel: {
  5503. eng: 'Display stubs access statistics and JSON filter',
  5504. rus: 'Выводить статистику запросов к заглушкам и JSON фильтра'
  5505. },
  5506. AbortExecutionStatisticsLabel: {
  5507. eng: 'Display abort execution statistics',
  5508. rus: 'Выводить статистику прерывания исполнения скриптов'
  5509. },
  5510. LogAttachedCSSLabel: {
  5511. eng: 'Log CSS attached to a page',
  5512. rus: 'Журналировать CSS добавленные на страницу'
  5513. },
  5514. BlockNotificationPermissionRequestsLabel: {
  5515. eng: 'Block requests to Show Notifications on sites',
  5516. rus: 'Блокировать запросы Показывать Уведомления на сайтах'
  5517. },
  5518. ShowScriptHandlerCompatibilityWarningLabel: {
  5519. eng: 'Show compatibility warning in menu next to Options',
  5520. rus: 'Отображать предупреждение о совместимости в меню рядом с Настройками'
  5521. },
  5522. reg(el, name) {
  5523. this[name].link = el;
  5524. this.linked.push(name);
  5525. },
  5526. setLang(lang = 'eng') {
  5527. for (let name of this.linked) {
  5528. const el = this[name].link;
  5529. const label = this[name][lang];
  5530. el.textContent = label;
  5531. }
  5532. this.langs.link.value = lang;
  5533. jsf.Lang = lang;
  5534. }
  5535. };
  5536.  
  5537. const _createTextNode = _Document.createTextNode.bind(_document);
  5538. const createOptionsWindow = () => {
  5539. const root = _createElement('div'),
  5540. shadow = _attachShadow ? _attachShadow(root, {
  5541. mode: 'closed'
  5542. }) : root,
  5543. overlay = _createElement('div'),
  5544. inner = _createElement('div');
  5545.  
  5546. overlay.id = 'overlay';
  5547. overlay.appendChild(inner);
  5548. shadow.appendChild(overlay);
  5549.  
  5550. inner.id = 'inner';
  5551. inner.br = function appendBreakLine() {
  5552. return this.appendChild(_createElement('br'));
  5553. };
  5554.  
  5555. createStyle({
  5556. 'h2': {
  5557. margin_top: 0
  5558. },
  5559. 'h2, h3': {
  5560. margin_block_end: '0.5em'
  5561. },
  5562. 'div, button, select, input': {
  5563. font_family: 'Helvetica, Arial, sans-serif',
  5564. font_size: '12pt'
  5565. },
  5566. 'button': {
  5567. background: 'linear-gradient(to bottom, #f0f0f0 5%, #c0c0c0 100%)',
  5568. border_radius: '3px',
  5569. border: '1px solid #a1a1a1',
  5570. color: '#000000',
  5571. text_shadow: '0px 1px 0px #d4d4d4'
  5572. },
  5573. 'button:hover': {
  5574. background: 'linear-gradient(to bottom, #c0c0c0 5%, #f0f0f0 100%)'
  5575. },
  5576. 'button:active': {
  5577. position: 'relative',
  5578. top: '1px'
  5579. },
  5580. 'select': {
  5581. border: '1px solid darkgrey',
  5582. border_radius: '0px 0px 5px 5px',
  5583. border_top: '0px'
  5584. },
  5585. 'button:focus, select:focus': {
  5586. outline: 'none'
  5587. },
  5588. '#overlay': {
  5589. position: 'fixed',
  5590. top: 0,
  5591. left: 0,
  5592. bottom: 0,
  5593. right: 0,
  5594. background: 'rgba(0,0,0,0.65)',
  5595. z_index: 2147483647 // Highest z-index: Math.pow(2, 31) - 1
  5596. },
  5597. '#inner': {
  5598. background: 'whitesmoke',
  5599. color: 'black',
  5600. padding: '1.5em 1em 1.5em 1em',
  5601. max_width: '150ch',
  5602. position: 'absolute',
  5603. top: '50%',
  5604. left: '50%',
  5605. transform: 'translate(-50%, -50%)',
  5606. border: '1px solid darkgrey',
  5607. border_radius: '5px'
  5608. },
  5609. '#closeOptionsButton': {
  5610. float: 'right',
  5611. transform: 'translate(1em, -1.5em)',
  5612. border: 0,
  5613. border_radius: 0,
  5614. background: 'none',
  5615. box_shadow: 'none'
  5616. },
  5617. '#selectLang': {
  5618. float: 'right',
  5619. transform: 'translate(0, -1.5em)'
  5620. },
  5621. '.optionsLabel': {
  5622. padding_left: '1.5em',
  5623. text_indent: '-1em',
  5624. display: 'block'
  5625. },
  5626. '.optionsCheckbox': {
  5627. left: '-0.25em',
  5628. width: '1em',
  5629. height: '1em',
  5630. padding: 0,
  5631. margin: 0,
  5632. position: 'relative',
  5633. vertical_align: 'middle'
  5634. },
  5635. '@media (prefers-color-scheme: dark)': {
  5636. '#inner': {
  5637. background_color: '#292a2d',
  5638. color: 'white',
  5639. border: '1px solid #1a1b1e'
  5640. },
  5641. 'input': {
  5642. filter: 'invert(100%)'
  5643. },
  5644. 'button': {
  5645. background: 'linear-gradient(to bottom, #575757 5%, #303030 100%)',
  5646. border_color: '#575757',
  5647. color: '#f0f0f0',
  5648. text_shadow: '0px 1px 0px #171717'
  5649. },
  5650. 'button:hover': {
  5651. background: 'linear-gradient(to bottom, #303030 5%, #575757 100%)'
  5652. },
  5653. 'select': {
  5654. background_color: '#303030',
  5655. color: '#f0f0f0',
  5656. border: '1px solid #1a1b1e',
  5657. border_radius: '0px 0px 5px 5px',
  5658. border_top: '0px'
  5659. },
  5660. '#overlay': {
  5661. background: 'rgba(0,0,0,.85)',
  5662. }
  5663. }
  5664. }, {
  5665. root: shadow,
  5666. protect: false
  5667. });
  5668.  
  5669. // components
  5670. function createCheckbox(name) {
  5671. const checkbox = _createElement('input'),
  5672. label = _createElement('label');
  5673. checkbox.type = 'checkbox';
  5674. checkbox.classList.add('optionsCheckbox');
  5675. checkbox.checked = jsf[name];
  5676. checkbox.onclick = e => {
  5677. jsf[name] = e.target.checked;
  5678. return true;
  5679. };
  5680. label.classList.add('optionsLabel');
  5681. label.appendChild(checkbox);
  5682. const text = _createTextNode('');
  5683. label.appendChild(text);
  5684. Object.defineProperty(label, 'textContent', {
  5685. set(title) {
  5686. text.textContent = title;
  5687. }
  5688. });
  5689. return label;
  5690. }
  5691.  
  5692. // language & close
  5693. const closeBtn = _createElement('button');
  5694. closeBtn.onclick = () => _removeChild(root);
  5695. closeBtn.textContent = '\u2715';
  5696. closeBtn.id = 'closeOptionsButton';
  5697. inner.appendChild(closeBtn);
  5698.  
  5699. overlay.addEventListener('click', e => {
  5700. if (e.target === overlay) {
  5701. _removeChild(root);
  5702. e.preventDefault();
  5703. }
  5704. e.stopPropagation();
  5705. }, false);
  5706.  
  5707. const selectLang = _createElement('select');
  5708. for (let name in lines.langs) {
  5709. const langOption = _createElement('option');
  5710. langOption.value = name;
  5711. langOption.innerText = lines.langs[name];
  5712. selectLang.appendChild(langOption);
  5713. }
  5714. selectLang.id = 'selectLang';
  5715. lines.langs.link = selectLang;
  5716. inner.appendChild(selectLang);
  5717.  
  5718. selectLang.onchange = e => {
  5719. const lang = e.target.value;
  5720. lines.setLang(lang);
  5721. };
  5722.  
  5723. // fill options form
  5724. const header = _createElement('h2');
  5725. header.textContent = 'RU AdList JS Fixes';
  5726. inner.appendChild(header);
  5727.  
  5728. lines.reg(inner.appendChild(_createElement('h3')), 'HeaderTools');
  5729.  
  5730. const sObjBtn = _createElement('button');
  5731. sObjBtn.onclick = getStrangeObjectsList;
  5732. sObjBtn.textContent = '';
  5733. lines.reg(inner.appendChild(sObjBtn), 'sObjBtn');
  5734.  
  5735. lines.reg(inner.appendChild(_createElement('h3')), 'HeaderOptions');
  5736.  
  5737. lines.reg(inner.appendChild(createCheckbox('AccessStatistics')), 'AccessStatisticsLabel');
  5738. lines.reg(inner.appendChild(createCheckbox('AbortExecutionStatistics')), 'AbortExecutionStatisticsLabel');
  5739. lines.reg(inner.appendChild(createCheckbox('LogAttachedCSS')), 'LogAttachedCSSLabel');
  5740.  
  5741. inner.appendChild(_createElement('br'));
  5742. lines.reg(inner.appendChild(createCheckbox('BlockNotificationPermissionRequests')), 'BlockNotificationPermissionRequestsLabel');
  5743.  
  5744. if (incompatibleScriptHandler) {
  5745. inner.appendChild(_createElement('br'));
  5746. lines.reg(inner.appendChild(createCheckbox('ShowScriptHandlerCompatibilityWarning')), 'ShowScriptHandlerCompatibilityWarningLabel');
  5747. }
  5748.  
  5749. lines.setLang(jsf.Lang);
  5750.  
  5751. return root;
  5752. };
  5753.  
  5754. let optionsWindow;
  5755. GM_registerMenuCommand(lines.MenuOptions[jsf.Lang], () => _appendChild(optionsWindow = optionsWindow || createOptionsWindow()));
  5756. // add warning to script menu for non-Tampermonkey users
  5757. if (jsf.ShowScriptHandlerCompatibilityWarning && incompatibleScriptHandler)
  5758. GM_registerMenuCommand(`${GM.info.scriptHandler} ${lines.MenuCompatibilityWarning[jsf.Lang]}`, () => {
  5759. win.open(`https://greasyfork.org/${opts.Lang.slice(0,2)}/scripts/19993-ru-adlist-js-fixes#additional-info`);
  5760. });
  5761. }
  5762. })();