Welcome to a tutorial on how to pass variables between pages in Javascript. Need to pass some data between different pages?
An easy way to pass variables between pages is to use a query string:
- On the first page:
var para = new URLSearchParams();
para.append("KEY", "VALUE");
location.href = "HTTP://SITE.COM/PAGE.HTML?" + para.toString();
- On the second page:
var para = new URLSearchParams(window.location.search);
var pass = para.get("KEY");
But there are more methods that we can use. Let us walk through some examples in this guide, and what is a better way to deal with things – Read on!
ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.
QUICK SLIDES
TABLE OF CONTENTS
DOWNLOAD & NOTES
Firstly, here is the download link to the example code as promised.
QUICK NOTES
- Take note that some of these examples will not work with
file://
. Use a proper web server withhttp://
instead.
EXAMPLE CODE DOWNLOAD
Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
HOW TO PASS VARIABLES BETWEEN PAGES
All right, let us now get into the ways to pass variables between pages in Javascript.
METHOD 1) SESSION STORAGE
<script>
function store () {
// (A) VARIABLES TO PASS
var first = "Foo Bar",
second = ["Hello", "World"];
// (B) SAVE TO SESSION STORAGE
// (B1) FLAT STRING OR NUMBER
// SESSIONSTORAGE.SETITEM("KEY", "VALUE");
sessionStorage.setItem("first", first);
// (B2) ARRAY OR OBJECT
// SESSION STORAGE CANNOT STORE ARRAY AND OBJECTS
// JSON ENCODE BEFORE STORING, CONVERT TO STRING
sessionStorage.setItem("second", JSON.stringify(second));
// (C) REDIRECT
location.href = "1b-session.html";
// window.open("1b-session.html");
}
</script>
<input type="button" value="Store To Session Storage" onclick="store()"/>
<script>
function get () {
// (A) GET FROM SESSION
var first = sessionStorage.getItem("first"),
second = JSON.parse(sessionStorage.getItem("second"));
// (B) IT WORKS!
// MANUALLY OPENING 1B-SESSION.HTML WILL NOT WORK THOUGH
// SESSION DATA WILL PERISH ONCE TAB/WINDOW IS CLOSED
console.log(first); // Foo Bar
console.log(second); // ["Hello", "World"]
// (EXTRA) CLEAR SESSION STORAGE
// sessionStorage.removeItem("KEY");
// sessionStorage.clear();
}
</script>
<input type="button" value="Get From Session Storage" onclick="get()"/>
Yep, no need for any gimmicks. There is a temporary “sandbox” storage area in Javascript called session storage. Very easy to use, only 4 functions to know:
sessionStorage.setItem(KEY, VALUE)
sessionStorage.getItem(KEY)
sessionStorage.removeItem(KEY)
sessionStorage.clear()
But please take note that the session storage will be automatically deleted once the user closes the tab/window.
P.S. Data will also not be passed when the user manually opens another tab/window.
METHOD 2) LOCAL STORAGE
<script>
function store () {
// (A) VARIABLES TO PASS
var first = "Foo Bar",
second = ["Hello", "World"];
// (B) SAVE TO LOCAL STORAGE
// (B1) FLAT STRING OR NUMBER
// LOCALSTORAGE.SETITEM("KEY", "VALUE");
localStorage.setItem("first", first);
// (B2) ARRAY OR OBJECT
// LOCAL STORAGE CANNOT STORE ARRAY AND OBJECTS
// JSON ENCODE BEFORE STORING, CONVERT TO STRING
localStorage.setItem("second", JSON.stringify(second));
// (C) REDIRECT OR OPEN NEW WINDOW IF YOU WANT
location.href = "2b-local-storage.html";
// window.open("2b-local-storage.html");
}
</script>
<input type="button" value="Store To Local Storage" onclick="store()"/>
<script>
function get () {
// (A) GET FROM SESSION
var first = localStorage.getItem("first"),
second = JSON.parse(localStorage.getItem("second"));
// (B) IT WORKS!
// NOTE: LOCAL STORAGE IS PERSISTENT
// WILL NOT BE DELETED UNLESS USER CLEARS BROWSER DATA OR MANUALLY CLEARED
console.log(first); // Foo Bar
console.log(second); // ["Hello", "World"]
// (EXTRA) CLEAR LOCAL STORAGE
// localStorage.removeItem("KEY");
// localStorage.clear();
}
</script>
<input type="button" value="Get From Local Storage" onclick="get()"/>
Looks familiar? Because local storage is the cousin of session storage. Yep, the same old temporary storage area, but local storage is persistent – Whatever is set in the local storage will stay until manually deleted; Yep, we can still retrieve data from the local storage even after the window is closed and reopened later.
METHOD 3) URL PARAMETERS
<script>
function go () {
// (A) VARIABLES TO PASS
var first = "Foo Bar",
second = ["Hello", "World"];
// (B) URL PARAMETERS
var params = new URLSearchParams();
params.append("first", first);
params.append("second", JSON.stringify(second));
// (C) GO!
var url = "3b-query.html?" + params.toString();
location.href = url;
// window.open(url);
}
</script>
<input type="button" value="GO" onclick="go()"/>
<script>
function get () {
// (A) GET THE PARAMETERS
var params = new URLSearchParams(window.location.search),
first = params.get("first"),
second = JSON.parse(params.get("second"));
// (B) IT WORKS!
console.log(first); // Foo Bar
console.log(second); // ["Hello", "World"]
}
</script>
<input type="button" value="Get" onclick="get()"/>
You might have already heard of GET
variables, appending a ?KEY=VALUE
query string behind the URL. Yep, Javascript is fully capable of getting the query string, and we can use that to pass data.
METHOD 4) COOKIE STORAGE
<script>
function store () {
// (A) VARIABLES TO PASS
var first = "Foo Bar",
second = ["Hello", "World"];
// (B) URL PARAMETERS + STORE INTO COOKIE
// * WORKS, BUT NOT RECOMMENDED
var params = new URLSearchParams();
params.append("first", first);
params.append("second", JSON.stringify(second));
document.cookie = "pass=" + params.toString();
// (C) REDIRECT
location.href = "4b-cookie.html";
// window.open("4b-cookie.html");
}
</script>
<input type="button" value="Go" onclick="store()"/>
<script>
function get () {
// (A) GET BACK PASS VARS
var passvars = document.cookie
.split("; ")
.find(row => row.startsWith("pass"))
.substring(5);
// (B) PARSE BACK
var params = new URLSearchParams(passvars),
first = params.get("first"),
second = JSON.parse(params.get("second"));
// (C) IT WORKS!
console.log(first); // Foo Bar
console.log(second); // ["Hello", "World"]
}
</script>
<input type="button" value="Get" onclick="get()"/>
You might have also heard of the cookie, a small token to keep some data… Anyway, just don’t mess with the cookie unless really necessary. Keep this one as a last desperate resort.
METHOD 5) NEW WINDOW
<script>
function go () {
// (A) VARIABLES TO PASS
var first = "Foo Bar",
second = ["Hello", "World"];
// (B) OPEN NEW WINDOW
// JUST PASS VARIABLES OVER TO NEW WINDOW
var newwin = window.open("5b-window.html");
newwin.onload = () => {
newwin.first = first;
newwin.second = second;
};
}
</script>
<input type="button" value="GO" onclick="go()"/>
<script>
function get () {
console.log(first); // Foo Bar
console.log(second); // ["Hello", "World"]
}
</script>
<input type="button" value="Get" onclick="get()"/>
When we create a new var newwin = window.open()
, we can “directly” insert the variables into the new window. As simple as that.
USEFUL BITS & LINKS
That’s all for this guide, and here is a small section on some extras and links that may be useful to you.
UPDATE THE PROCESSES!
The Stone Age of the Internet is long past. Instead of reloading and redirecting pages, we really should be looking at creating a “seamless” experience with modern technologies instead. For example, if we want to create a wizard-style form where the user chooses an option in step 1, then pass it to step 2 – We can use AJAX to drive the entire application.
<script>
function next () {
// (A) GET SELECTED VALUE
var selected = document.querySelector("#stepA input[type=radio]:checked").value;
// (B) LOAD FORM VIA AJAX
var xhr = new XMLHttpRequest();
xhr.open("POST", "6b-ajax.html");
xhr.onload = function () {
// HIDE STEP A
document.getElementById("stepA").style.display = "none";
// SET LOADED HTML AND SELECTED
document.getElementById("stepB").innerHTML = this.response;
document.getElementById("radsel").value = selected;
// SHOW STEP B
document.getElementById("stepB").style.display = "block";
};
xhr.send();
}
</script>
<!-- (A) SELECT ITEM -->
<div id="stepA">
<label>
<input type="radio" name="radopt" value="Foo" checked/> Foo
</label>
<label>
<input type="radio" name="radopt" value="Bar"/> Bar
</label>
<input type="button" value="Next" onclick="next()"/>
</div>
<!-- (B) FORM -->
<div id="stepB" style="display:none"></div>
<form onsubmit="alert('OK'); return false;">
Selected: <input type="text" id="radsel" name="radsel" readonly/>
Name: <input type="text" name="username" required/>
Email: <input type="email" name="useremail" required/>
<input type="submit" value="Go"/>
</form>
LINKS & REFERENCES
- Window.sessionStorage – MDN
- Window.localStorage – MDN
- URL Search Params – MDN
- Document.cookie – MDN
- Pass Javascript Variables to Another Page – lage.us
- Beginner AJAX Tutorial – Code Boxx
TUTORIAL VIDEO
INFOGRAPHIC CHEAT SHEET

THE END
Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!