JavaScript Session storage variable on another page

Solution 1:

You can pass sessionStorage as as query string at href of <a> element; use location.search at window.onload event at Page2.html

Page1.html

<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="style.css">
  <script src="script.js"></script>
</head>

<body>
  <a href="Page2.html" data-color="red" onclick="color(this)">Set color to red</a>
  <a href="Page2.html" data-color="blue" onclick="color(this)">Set color to blue</a>
  <a href="Page2.html" data-color="green" onclick="color(this)">Set color to green</a>

  <script>
    function color(elem) {
      event.preventDefault();
      sessionStorage.setItem("colorVar", elem.dataset.color);
      location.href = elem.href + "?colorVar=" + sessionStorage.getItem("colorVar");
    }
  </script>
</body>

</html>

at Page2.html

<script>
window.onload = function() {
  document.write("Your color is " + location.search.split("=").pop())
}
</script>

plnkr http://plnkr.co/edit/eNVXr4ElXRzrxlZ7EY0a?p=preview

Solution 2:

Edit: Clearly the answer above is much better than what i provided. I'll leave this here for future viewers - maybe the way I phrased things help someone sometime.


Taylor,

Two things.

  1. sessionStorage() is unique to each page/tab. From the docs "Opening a page in a new tab or window will cause a new session to be initiated"

  2. window.onload is expecting a function. You're just concatenating a string.

If you find a different way to pass information from one page to another (you could stuff it in the URL) your new color function should look something like this:

<script>
window.onload = writeColor(sessionStorage.colorVar);

function writeColor(color) {
  document.write("Your color is " + color + "!")
}
</script>