Pass Javascript Variables to Another Page

There are two ways to pass variables between web pages. The first method is to use sessionStorage, or localStorage. The second method is to use a query string with the URL.

sessionStorage or localStorage:

// This goes in the first web page:
// "favoriteMovie" is the sessionStorage variable name
// "Shrek" is the variable string value
sessionStorage.setItem("favoriteMovie", "Shrek");
 
// This goes in the second web page:
// Retrieve the sessionStorage variable
var favoriteMovie = sessionStorage.getItem('favoriteMovie');

Example 1:

Javascript in Page 1:
var favoritemovie = "Shrek";
sessionStorage.setItem("favoriteMovie", favoritemovie);

Javascript in Page 2:
var favoritemovie = sessionStorage.getItem("favoriteMovie");
console.log(favoritemovie);

Prints this result in the console:
Shrek

Example 2:

You can pass an array from one page to another by converting the array to a string before saving to a variable in sessionStorage.

Javascript array in Page 1:
jsarray = ["cat", "dog", "tiger", "wolf"];
sessionStorage.setItem("jsArray", JSON.stringify(jsarray));

// JSON.stringify(jsArray) converts the jsArray into a string which can be stored in sessionStorage

Javascript array in Page 2:
jsarray = JSON.parse(sessionStorage.getItem("jsArray"));

// the javascript array jsarray is now in Page 2 as ["cat", "dog", "tiger", "wolf"]


Method 2

Of course there's another way to do it...

Pass a string as a parameter.

Example: <a href="filename.html?data1|data2|data3">Go to filename</a>

When Go to filename is clicked, filename.html is loaded with the query string "?data1|data2|data3" appended to the filename in the address bar. To get the query string into variables,
use: var queryString = location.search.substring(1);

The variable queryString now has the value "data1|data2|data3".
To break these out into individual variables use split:

var a = queryString.split("|"); // which creates an array

Then get the values out of the array and put them into variables:
var value1 = a[0];
var value2 = a[1];
var value3 = a[2];

Now:
value1 == "data1", value2 == "data2", value3 == "data3"