Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I append a query parameter to my URL using Javascript?

I am building a web app and I am using Firebase to store my user's data in Cloud Firestore. There is a page on my web app that allows users to view their documents from Cloud Firestore. I would like to add a query parameter to the end of my URL on view.html so I can take that query parameter value and use it to search for a document.

I have been searching online to find possible solutions. So far I have come across a few videos on the topic, but they haven't been going into the depth I have been needing. For example, this video shows how to add and get query parameters from a URL, but it only shows how to log those changes in the console. How would I make that my URL?

I've also be browsing Stackoverflow for solutions. This Stackoverflow post asks a similar question, however, many of the solutions in the answers causes view.html to reload on a loop. Why would this be, and if this is a possible solution, how would I stop this from happening.

How would I go about appending and fetching URL query parameters in Javascript?

like image 737
michaelderiso Avatar asked Jul 18 '26 10:07

michaelderiso


1 Answers

You say you want to do this in javascript, so I assume the page itself is building/modifying a link to either place on the page or go to directly via javascript.

In javascript in the browser there is the URL object, which can build and decompose URLs

let thisPage = new URL(window.location.href);
let thatPage = new URL("https://that.example.com/path/page");

In any case, once you have a URL object you can access the parts of it to read and set the values.

Adding a query parameter uses the searchParams attribute of the URL, where you can add parameters with the .append method — and you don't have to worry about managing the ? and & … the method takes care of that for you.

thisPage.searchParams.append('yourKey', 'someValue');

This demonstrates it live on this page, adding search parameters and displaying the URL at each step:

let here = new URL(window.location.href);
console.log(here);
here.searchParams.append('firstKey', 'theValue');
console.log(here);
here.searchParams.append('key2', 'another');
console.log(here);
like image 168
Stephen P Avatar answered Jul 19 '26 23:07

Stephen P