5 Ways to Pass Variables Between Pages In Javascript

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 Passing Variables Useful Bits & Links
Tutorial Video The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

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.

 

QUICK NOTES

  • Take note that some of these examples will not work with file://. Use a proper web server with http:// instead.

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

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

1a-session.html
<script>
function store () {
  // (A) VARIABLES TO PASS
  var first = "Foo Bar",
      second = ["Hello", "World"];
 
  // (B) SAVE TO SESSION STORAGE
  // sessionStorage.setItem("KEY", "VALUE");
  sessionStorage.setItem("first", first);
  // 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";
  // Opening new window works too
  // window.open("1b-session.html");
}
</script>

<input type="button" value="Store To Session Storage" onclick="store()"/>
1b-session.html
<script>
function get () {
  // (A) GET FROM SESSION
  var first = sessionStorage.getItem("first"),
      // JSON parse to turn stored sting back into array
      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) TO CLEAR
  // 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

2a-local-storage.html
<script>
function store () {
  // (A) VARIABLES TO PASS
  var first = "Foo Bar",
      second = ["Hello", "World"];

  // (B) SAVE TO LOCAL STORAGE
  // localStorage.setItem("KEY", "VALUE");
  localStorage.setItem("first", first);
  // 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
  // window.open("2b-local-storage.html");
  location.href = "2b-local-storage.html";
}
</script>

<input type="button" value="Store To Local Storage" onclick="store()"/>
2b-local-storage.html
<script>
function get () {
  // (A) GET FROM SESSION
  var first = localStorage.getItem("first"),
      // JSON parse to turn stored sting back into array
      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) TO CLEAR
  // 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

3a-query.html
<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()"/>
3b-query.html
<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

4a-cookie.html
<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()"/>
4b-cookie.html
<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

5a-window.html
<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 = function(){
    // "this" refers to newwin
    this.first = first;
    this.second = second;
  };
}
</script>

<input type="button" value="GO" onclick="go()"/>
5b-window.html
<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.

6a-ajax.html
<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><br>
  <input type="button" value="Next" onclick="next()"/>
</div>
 
<!-- (B) FORM -->
<div id="stepB" style="display:none"></div>
6b-ajax.html
<form onsubmit="alert('OK'); return false;">
  Selected: <input type="text" id="radsel" name="radsel" readonly/>
  <br>
  Name: <input type="text" name="username" required/>
  <br>
  Email: <input type="email" name="useremail" required/>
  <br>
  <input type="submit" value="Go"/>
</form>

 

 

LINKS & REFERENCES

 

TUTORIAL VIDEO

 

INFOGRAPHIC CHEAT SHEET

How To Pass Variables Between Pages In Javascript (click to enlarge)

 

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!

Leave a Comment

Your email address will not be published. Required fields are marked *