UNPKG

hd-utils

Version:

A handy utils for modern JS developers

84 lines (83 loc) 2.31 kB
import getWindow from '../utils/browser/getWindow'; import getUrlObj from '../utils/route/getUrlObj'; import isNullOrEmptyString from '../utils/validation/isNullOrEmptyString'; const window = getWindow(); /** *@important --Browser Only -- *@description A utility class for handling and updating URL parameters, paths, and fragments in the browser with/without page refresh." *@example const browserUrl = new BrowserURLUpdater("www.foo.com"); * browserUrl.setQueryParam("bar", "1"); // will set the url to "www.foo.com/?bar=1" and update the url without refresh. * */ export default class BrowserURLUpdater { constructor(url = window.location.href, reloadOnEveryChange) { this._state = {}; if (isNullOrEmptyString(url)) throw new Error('URL must be passed'); this._url = getUrlObj(url); this._reload = !!reloadOnEveryChange; } updateURL() { if (this._reload) { window.location.reload(); return; } window.history.pushState(this._state, '', this._url.toString()); } setQueryParam(key, value) { if (value !== undefined) { this._url.searchParams.set(key, value); } else { this._url.searchParams.delete(key); } this.updateURL(); } removeQueryParam(key) { this._url.searchParams.delete(key); this.updateURL(); } getQueryParam(key) { return this._url.searchParams.get(key); } getPath() { return this._url.pathname; } setPath(path) { this._url.pathname = path; this.updateURL(); } removePath() { this._url.pathname = '/'; this.updateURL(); } setFragment(fragment) { this._url.hash = fragment; this.updateURL(); } getFragment() { return this._url.hash; } removeFragment() { this._url.hash = ''; this.updateURL(); } set url(value) { this._url = getUrlObj(value); } get url() { return this._url.toString(); } get reload() { return this._reload; } set reload(value) { this._reload = value; } get state() { return this._state; } set state(value) { this._state = value; } }