@soleil-se/app-util
Version:
Utility functions for WebApps, RESTApps and Widgets in Sitevision.
56 lines (48 loc) • 1.44 kB
JavaScript
import { stringifyParams, parseParams } from '../../common';
const isEmpty = (obj) => Object.keys(obj).length === 0 && obj.constructor === Object;
/**
* Set query parameters in the url-field.
* @param {Object} obj - Values to be set.
* @param {Object} [options] Optional options.
* @param {Boolean} [options.scoped = false] If parameter keys should be scoped to current app.
*/
export function setUrlParams(params) {
const path = (isEmpty(params) ? window.location.pathname : `?${stringifyParams(params)}`);
const { hash = '' } = window.location;
window.history.replaceState({}, '', path + hash);
}
/**
* Get query parameter from the url-field.
*/
export function getUrlParam(key) {
const params = parseParams(window.location.search);
return params[key];
}
/**
* Get query parameters from the url-field.
*/
export function getUrlParams() {
const params = parseParams(window.location.search);
return params;
}
/**
* Clear query parameters in the url-field.
*/
export function clearUrlParams() {
const { pathname, hash = '' } = window.location;
window.history.replaceState({}, '', pathname + hash);
}
/**
* Updates query parameters in the url-field.
* @param {Object} params - Values to be updated.
*/
export function updateUrlParams(params) {
setUrlParams(Object.assign(getUrlParams(), params));
}
export default {
getUrlParam,
setUrlParams,
getUrlParams,
clearUrlParams,
updateUrlParams,
};