JS: Update URL Query String Parameter (window.location , window.history.pushState)
Problem:
if you have a Input Text Field such as a search box γsee XahLee.info Search πγ , and you want user to be able to use the URL to fetch the same search result they typed in the search box, what to do?
Solution:
make your code do 2 things:
- when the page is loaded, get the search text from the url parameter, fill it in the search box. (again, this is done only when the page loads.) Use
window.location.search
- When search box is changed, such as user typed something, update the url parameter. (use
window.history.pushState
)
Get the URL Parameter Value
here's how to get the url param values:
const searchBox_kqWNN = document.getElementById("searchBox_kqWNN"); { const xurlSearchStr = (new URLSearchParams(window.location.search)); if (xurlSearchStr) { ((<HTMLInputElement> searchBox_kqWNN).value) = xurlSearchStr.get("q"); } }
Set the URL Parameter Value
here's how to get set url param values, from a search box value:
const xurl: URL = (new URL(window.location.toString())); xurl.searchParams.set("q", ((<HTMLInputElement> searchBox_kqWNN).value)); window.history.pushState({}, "", xurl.toString());