Explain Codes LogoExplain Codes Logo

Appending parameter to URL without refresh

javascript
url-manipulation
browser-history
url-encoding
Nikita BarsukovbyNikita Barsukov·Jan 19, 2025
TLDR

Modify the URL by adding a new parameter without a page reload by utilizing the following line of code:

history.pushState(null, '', `${location.href}&newParam=value`);

This script uses history.pushState() to smoothly attach newParam=value to the existing URL.

To make this process more elegant, consider the URL and URLSearchParams objects, which allow for a cleaner manipulation:

const url = new URL(window.location); url.searchParams.append('newParam', 'value'); window.history.pushState({}, '', url);

Here, newParam is integrated as a query parameter while also taking care of any necessary encoding and URL structure.

Enhancing URL manipulations

window.location properties and the URL API provide an in-depth understanding of how URLs can be constructed and edited. By breaking down the URL structure into protocol, host, and pathname, we are able to insert parameters precisely where needed.

Seamless updates with replaceState

Just like pushState(), history.replaceState() is used to modify the URL. However, this function does not add the new URL to the history stack. This comes in handy when creating filter or search functionalities where a multitude of quick URL changes might saturate the browser history.

window.history.replaceState(null, null, '?newParam=value');

Encoding parameters: Playing it safe

When dealing with data that includes symbols not safe for URL use, it's crucial to ensure key/value pairs are correctly encoded:

const paramKey = encodeURIComponent('a bit naughty param&name'); const paramValue = encodeURIComponent('value with spaces, or worse'); history.pushState(null, '', `${location.href}?${paramKey}=${paramValue}`);

// Note: I'm innocent, officer. It's just URL encoding. 😬

This ensures your URL is kept standard-compliant.

Custom tailoring with complex updates

For those times when searchParams can't handle all your URL amendment needs, go for direct string manipulation coupled with pushState():

let url = new URL(window.location); let newUrl = `${url.protocol}//${url.host}${url.pathname}?${fancyUrlConcoctionFunction()}`; window.history.pushState(null, '', newUrl);

// Note: "fancyUrlConcoctionFunction()", it's like "fixEverythingFunction()" but for URLs. 🎩🍸

This approach gives room for custom logic like checking a parameter's existence before adding it, replacing existing parameters, or adding new ones.

Grouping parameters

When juggling multiple parameters, an easy way to combine them into a single query string is using jQuery's $.param() method:

let params = { first: 'value1', second: 'value2' }; let queryString = $.param(params); history.pushState(null, '', `${location.href}?${queryString}`);

// Note: Waiter, one neatly crafted URL with a side of params, please. 🍸

This effectively generates a properly formatted and encoded query string.

Handling "?" predicaments

When adding a parameter that begins with ?, consider the existing parameters. By doing so, you can effectively avoid duplication or syntax conflicts:

function updateUrlParameter(param, value) { const url = new URL(window.location); url.searchParams.set(param, value); window.history.pushState(null, '', url); }

This function smartly appends or replaces the parameter. It keeps the URL clean and tidy (and possibly a little smug).

The bigger picture

Various interactive user interfaces demand URL updates to preserve the current state. You can associate pushState() or replaceState() into actions like button clicks, applying filters, or submitting searches. Doing so morphs your application into an interactive canvas for the user.