2017-05-04 15:20:41 +00:00
|
|
|
/* @flow */
|
|
|
|
|
2018-07-21 15:16:32 +00:00
|
|
|
import { reportError } from '../util';
|
|
|
|
|
2017-05-04 15:20:41 +00:00
|
|
|
/**
|
2017-07-27 18:50:09 +00:00
|
|
|
* Parses the query/search or fragment/hash parameters out of a specific URL and
|
|
|
|
* returns them as a JS object.
|
2017-05-04 15:20:41 +00:00
|
|
|
*
|
2017-05-26 22:11:33 +00:00
|
|
|
* @param {string} url - The URL to parse.
|
2017-07-27 18:50:09 +00:00
|
|
|
* @param {boolean} dontParse - If falsy, some transformations (for parsing the
|
|
|
|
* value as JSON) will be executed.
|
|
|
|
* @param {string} source - If {@code 'search'}, the parameters will parsed out
|
|
|
|
* of {@code url.search}; otherwise, out of {@code url.hash}.
|
2017-05-04 15:20:41 +00:00
|
|
|
* @returns {Object}
|
|
|
|
*/
|
|
|
|
export default function parseURLParams(
|
|
|
|
url: URL,
|
|
|
|
dontParse: boolean = false,
|
|
|
|
source: string = 'hash'): Object {
|
|
|
|
const paramStr = source === 'search' ? url.search : url.hash;
|
|
|
|
const params = {};
|
2019-02-21 23:30:02 +00:00
|
|
|
const paramParts = (paramStr && paramStr.substr(1).split('&')) || [];
|
2017-05-04 15:20:41 +00:00
|
|
|
|
2019-02-21 23:30:02 +00:00
|
|
|
// Detect and ignore hash params for hash routers.
|
|
|
|
if (source === 'hash' && paramParts.length === 1) {
|
|
|
|
const firstParam = paramParts[0];
|
|
|
|
|
|
|
|
if (firstParam.startsWith('/') && firstParam.split('&').length === 1) {
|
|
|
|
return params;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
paramParts.forEach(part => {
|
2017-05-04 15:20:41 +00:00
|
|
|
const param = part.split('=');
|
|
|
|
const key = param[0];
|
|
|
|
|
|
|
|
if (!key) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
let value;
|
|
|
|
|
|
|
|
try {
|
|
|
|
value = param[1];
|
|
|
|
if (!dontParse) {
|
|
|
|
value
|
|
|
|
= JSON.parse(decodeURIComponent(value).replace(/\\&/, '&'));
|
|
|
|
}
|
|
|
|
} catch (e) {
|
2018-07-21 15:16:32 +00:00
|
|
|
reportError(
|
|
|
|
e, `Failed to parse URL parameter value: ${String(value)}`);
|
2017-05-04 15:20:41 +00:00
|
|
|
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
params[key] = value;
|
|
|
|
});
|
|
|
|
|
|
|
|
return params;
|
|
|
|
}
|