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

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