How To Pass Value From One HTML Page To Another Using JavaScript

CyberBotMachines
3 min readSep 4, 2021

Simple tutorial on passing values between HTML pages using power of JavaScript.

TL;DR Summary

If you have simple textual or numerical values you’d like to pass to another HTML page then it’s simplest to use URL parameters to do so.
(see the next section for more details on how to pass objects etc.)

You can set URL param values in two ways.

First way you can pass values from one page to another is by adding it to the link directly:
<a href=”second_page.html?greeting=hello”>link</a>
and the second way is to do it through JavaScript:
window.location.href = “/second_page.html?greeting=hello”;
(this will have the same effect as if you clicked the link)

Simpler way to do it is by adding it to the link which is fine when you have static values. But in case of variables your only option is JavaScript.

And then all you have to do on the second page is just read the values from the URL params.

More Details

If you want to pass entire objects then doing so through URL parameters might not be practical.

Also don’t forget that there is 2000 character limit on the URL size. That means that the amount of data you can pass through URL is very limited.

So in that case it would be best to use localStorage object that is already available in your browser.

So what is localStorage?

This is simply an object that you can access from any page on your website.

What is great about it is whatever values you save to localStorage, those values are immediately available to all of your pages.

So it doesn’t matter if you go from one page to another because everything that you stored in localStorage keeps following you around.

Here is the simple example how you can use it on your website:

IMPORTANT:
There is one tricky thing about localStorage: it will not save objects.

What you need to do is to turn your object into JSON string and save it like that to localStorage. And then when you want to use it on some other page you can transform it back to regular object.

Here is how you turn object to string:
JSON.stringify(myObject);

Here is how you turn string back to object:
JSON.parse(myObjectString);

And here is some actual code example:

And if you want to delete all the data from localStorage then do this:
localStorage.clear();

And this is really all there is to passing value from one html page to another using JavaScript.

Also, you might like the articles about JavaScript img onclick events, as well as html input currency and textarea default value.

Until next time,
Will
Senior Developer & SEO Algo Specialist

==> FYI — if you want to build a startup with high success rate — then learn how to get FREE web traffic to your website. Because without web traffic you don’t have a startup — you have a dream.

--

--