UNPKG

@geogirafe/lib-geoportal

Version:

GeoGirafe is a flexible application to build online geoportals.

91 lines (90 loc) 2.71 kB
// SPDX-License-Identifier: Apache-2.0 import GirafeSingleton from '../../base/GirafeSingleton.js'; export default class UrlManager extends GirafeSingleton { getParam(param) { return new URL(globalThis.location.href).searchParams.get(param); } /** * Read all the arguments from the current url */ getParams(...args) { const url = new URL(globalThis.location.href); const result = {}; for (const arg of args) { result[arg] = url.searchParams.get(arg); } return result; } getParamsWithPrefix(...prefixList) { const url = new URL(globalThis.location.href); const result = {}; for (const prefix of prefixList) { for (const [key, value] of url.searchParams) { if (key.startsWith(prefix)) { result[key] = value; } } } return result; } /** * Remove the arguments from the current url */ removeParams(...args) { const url = new URL(globalThis.location.href); for (const arg of args) { url.searchParams.delete(arg); } this.updateUrl(url); } /** * Return the current root URL */ getRootUrl() { const currentUrl = new URL(globalThis.location.href); const pathname = currentUrl.pathname.substring(0, currentUrl.pathname.lastIndexOf('/') + 1); const baseUrl = `${currentUrl.protocol}//${currentUrl.host}${pathname}`; return baseUrl; } /** * Return the current url without the url parameters */ getBaseUrlPath() { const currentUrl = new URL(globalThis.location.href); const baseUrl = `${currentUrl.protocol}//${currentUrl.host}${currentUrl.pathname}`; return baseUrl; } /** * Replace the url in the browser * @param url url to replace * @param data optional data to pass to replaceState */ updateUrl(url, data) { globalThis.history.replaceState(data, '', url); } /** * Update the hash of the url */ updateHash(hash) { const url = new URL(globalThis.location.href); url.hash = hash; this.updateUrl(url); } /** * Get the current hash from the url */ getHash() { const url = new URL(globalThis.location.href); if (url.hash.length > 0 && url.hash.startsWith('#')) { return url.hash.substring(1); } return null; } /** * Check if the url contains the searched hash */ hasHash(searchedHash) { const hash = this.getHash(); return hash === searchedHash; } }