JavaScript: Update URL Query String Parameter (window.location , window.history.pushState)

By Xah Lee. Date: .

Problem:

if you have a Input Text Field such as a search box [see Xah Code 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:

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());

JavaScript/DOM, Get/Set URL

BUY
Ξ£JS
JavaScript in Depth

DOM Scripting

Overview

DOM Methods

Basic Examples

HTML Input

Web Scripting Examples

Web Scripting Misc