You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

parseURLParams.ts 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // @ts-ignore
  2. import { safeJsonParse } from '@jitsi/js-utils/json';
  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 (!url) {
  26. return {};
  27. }
  28. if (typeof url === 'string') {
  29. // eslint-disable-next-line no-param-reassign
  30. url = new URL(url);
  31. }
  32. const paramStr = source === 'search' ? url.search : url.hash;
  33. const params: any = {};
  34. const paramParts = paramStr?.substr(1).split('&') || [];
  35. // Detect and ignore hash params for hash routers.
  36. if (source === 'hash' && paramParts.length === 1) {
  37. const firstParam = paramParts[0];
  38. if (firstParam.startsWith('/') && firstParam.split('&').length === 1) {
  39. return params;
  40. }
  41. }
  42. paramParts.forEach((part: string) => {
  43. const param = part.split('=');
  44. const key = param[0];
  45. if (!key || key.split('.').some((k: string) => blacklist.includes(k))) {
  46. return;
  47. }
  48. let value;
  49. try {
  50. value = param[1];
  51. if (!dontParse) {
  52. const decoded = decodeURIComponent(value).replace(/\\&/, '&')
  53. .replace(/[\u2018\u2019]/g, '\'')
  54. .replace(/[\u201C\u201D]/g, '"');
  55. value = decoded === 'undefined' ? undefined : safeJsonParse(decoded);
  56. }
  57. } catch (e: any) {
  58. reportError(
  59. e, `Failed to parse URL parameter value: ${String(value)}`);
  60. return;
  61. }
  62. params[key] = value;
  63. });
  64. return params;
  65. }