RU AdList JS Fixes

try to take over the world!

当前为 2021-01-31 提交的版本,查看 最新版本

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