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.6KB

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