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:
window.location.href = “/second_page.html?greeting=hello”;
(this will have the same effect as if you clicked the link)
And then all you have to do on the second page is just read the values from the URL params.
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:
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:
Here is how you turn string back to object:
And here is some actual code example:
And if you want to delete all the data from localStorage then do this:
Until next time,
Senior Developer Content Writer
==> 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.