RU AdList JS Fixes

try to take over the world!

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

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