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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. // eslint-disable-next-line newline-per-chained-call
  21. paramStr && paramStr.substr(1).split('&').forEach(part => {
  22. const param = part.split('=');
  23. const key = param[0];
  24. if (!key) {
  25. return;
  26. }
  27. let value;
  28. try {
  29. value = param[1];
  30. if (!dontParse) {
  31. value
  32. = JSON.parse(decodeURIComponent(value).replace(/\\&/, '&'));
  33. }
  34. } catch (e) {
  35. reportError(
  36. e, `Failed to parse URL parameter value: ${String(value)}`);
  37. return;
  38. }
  39. params[key] = value;
  40. });
  41. return params;
  42. }