From aac9b6d59a327839730fe8f942c4df70e9e5b2bd Mon Sep 17 00:00:00 2001 From: Matt Mo Date: Thu, 25 Nov 2021 12:42:21 -0800 Subject: [PATCH] Added better support for query parameters in hash mode. --- ignite-html-router.js | 33 ++++++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/ignite-html-router.js b/ignite-html-router.js index 190072a..faf02e4 100644 --- a/ignite-html-router.js +++ b/ignite-html-router.js @@ -258,8 +258,8 @@ class Router { static navigate(route, data = null, refresh = false) { if (refresh) { if (Router.hashMode) { - //In hash mode the route can't start with /, we have to handle it here. - if (route.startsWith("/")) { + //In hash mode the route can't start with / or #, we have to handle it here. + if (route.startsWith("/") || route.startsWith("#")) { route = route.substr(1); } @@ -270,8 +270,8 @@ class Router { } } else { if (Router.hashMode) { - //In hash mode the route can't start with /, we have to handle it here. - if (route.startsWith("/")) { + //In hash mode the route can't start with / or #, we have to handle it here. + if (route.startsWith("/") || route.startsWith("#")) { route = route.substr(1); } @@ -328,7 +328,15 @@ class Router { //If hash mode is set and we have a hash location, get it and split it. if (Router.hashMode && window.location.hash && window.location.hash.length > 0) { - pathParts = window.location.hash.substr(1).split("/"); + var path = window.location.hash.substr(1); + + //If the path contains ? then remove the query. + if (path.includes("?")) { + path = path.split("?")[0]; + } + + //Break the path into path parts. + pathParts = path.split("/"); if (pathParts.length > 0 && pathParts[0].length == 0) { pathParts.splice(1); } @@ -417,6 +425,21 @@ class Router { return false; } } + + /** + * Returns a query parameter from the route search if there is one by it's name. + * @param {String} name The name of the query parameter to get. + * @returns {String} Null if not found, or the value of the query parameter. + */ + static getParameter(name) { + if (Router.hashMode) { + var params = new URLSearchParams(window.location.hash.includes("?") ? "?" + window.location.hash.split("?")[1] : ""); + return (params.has(name) ? params.get(name) : null); + } else { + var params = new URLSearchParams(window.location.search); + return (params.has(name) ? params.get(name) : null); + } + } } Router.states = [];