RU AdList JS Fixes

try to take over the world!

目前為 2020-10-21 提交的版本,檢視 最新版本

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