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.js 1.9KB

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