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