Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

parseURLParams.ts 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // @ts-ignore
  2. import Bourne from '@hapi/bourne';
  3. import { reportError } from './helpers';
  4. /**
  5. * A list if keys to ignore when parsing.
  6. *
  7. * @type {string[]}
  8. */
  9. const blacklist = [ '__proto__', 'constructor', 'prototype' ];
  10. /**
  11. * Parses the query/search or fragment/hash parameters out of a specific URL and
  12. * returns them as a JS object.
  13. *
  14. * @param {URL} url - The URL to parse.
  15. * @param {boolean} dontParse - If falsy, some transformations (for parsing the
  16. * value as JSON) will be executed.
  17. * @param {string} source - If {@code 'search'}, the parameters will parsed out
  18. * of {@code url.search}; otherwise, out of {@code url.hash}.
  19. * @returns {Object}
  20. */
  21. export function parseURLParams(
  22. url: URL | string,
  23. dontParse = false,
  24. source = 'hash') {
  25. if (typeof url === 'string') {
  26. // eslint-disable-next-line no-param-reassign
  27. url = new URL(url);
  28. }
  29. const paramStr = source === 'search' ? url.search : url.hash;
  30. const params: any = {};
  31. const paramParts = paramStr?.substr(1).split('&') || [];
  32. // Detect and ignore hash params for hash routers.
  33. if (source === 'hash' && paramParts.length === 1) {
  34. const firstParam = paramParts[0];
  35. if (firstParam.startsWith('/') && firstParam.split('&').length === 1) {
  36. return params;
  37. }
  38. }
  39. paramParts.forEach((part: string) => {
  40. const param = part.split('=');
  41. const key = param[0];
  42. if (!key || key.split('.').some((k: string) => blacklist.includes(k))) {
  43. return;
  44. }
  45. let value;
  46. try {
  47. value = param[1];
  48. if (!dontParse) {
  49. const decoded = decodeURIComponent(value).replace(/\\&/, '&');
  50. value = decoded === 'undefined' ? undefined : Bourne.parse(decoded);
  51. }
  52. } catch (e: any) {
  53. reportError(
  54. e, `Failed to parse URL parameter value: ${String(value)}`);
  55. return;
  56. }
  57. params[key] = value;
  58. });
  59. return params;
  60. }