RU AdList JS Fixes

try to take over the world!

目前為 2021-01-30 提交的版本,檢視 最新版本

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