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. /**
  3. * Parses the query/search or fragment/hash parameters out of a specific URL and
  4. * returns them as a JS object.
  5. *
  6. * @param {string} url - The URL to parse.
  7. * @param {boolean} dontParse - If falsy, some transformations (for parsing the
  8. * value as JSON) will be executed.
  9. * @param {string} source - If {@code 'search'}, the parameters will parsed out
  10. * of {@code url.search}; otherwise, out of {@code url.hash}.
  11. * @returns {Object}
  12. */
  13. export default function parseURLParams(
  14. url: URL,
  15. dontParse: boolean = false,
  16. source: string = 'hash'): Object {
  17. const paramStr = source === 'search' ? url.search : url.hash;
  18. const params = {};
  19. // eslint-disable-next-line newline-per-chained-call
  20. paramStr && paramStr.substr(1).split('&').forEach(part => {
  21. const param = part.split('=');
  22. const key = param[0];
  23. if (!key) {
  24. return;
  25. }
  26. let value;
  27. try {
  28. value = param[1];
  29. if (!dontParse) {
  30. value
  31. = JSON.parse(decodeURIComponent(value).replace(/\\&/, '&'));
  32. }
  33. } catch (e) {
  34. const msg = `Failed to parse URL parameter value: ${String(value)}`;
  35. console.warn(msg, e);
  36. window.onerror && window.onerror(msg, null, null, null, e);
  37. return;
  38. }
  39. params[key] = value;
  40. });
  41. return params;
  42. }