[RESOLVED] Trying to retrieve a session variable in Javascript?
I have two html pages, NO ASPX. I use javascript like this:
Code:
sessionStorage.setItem("locale", "photos/BOP")
To capture the value of "photos/BOP" and that works fine. I want to retrieve this value in the 2nd html page using javascript. I have my body tag set up like this:
HTML Code:
<body onload="getImages()">
Here is the getImages function in the 2nd html page:
Code:
function getImages() {
var fileextension = "jpg";
var dir = sessionStorage.getItem("locale");
alert(dir);
}
When the value is shown in the alert statement, it's NULL. What am I doing wrong
Re: Trying to retrieve a session variable in Javascript?
Re: Trying to retrieve a session variable in Javascript?
Quote:
Originally Posted by
blakemckenna
Any ideas on this???
How are you setting the sessionStorage value? Is this running under a local web server? Are you using http or https to access the web pages?
Re: Trying to retrieve a session variable in Javascript?
What I suspect is happening is that the body's onload event is firing before the sessionStorage values are accessible.
Does using this work:
HTML Code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>blakemckenna - example</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>blakemckenna - example</h1>
<p>locale: <span id="locale"></span></p>
<script>
window.addEventListener('load', function() {
var locale = sessionStorage.getItem('locale');
document.getElementById('locale').innerHTML = locale;
}, false);
</script>
</body>
</html>
Re: Trying to retrieve a session variable in Javascript?
I actually figured it out by using localStorage.setItem & localStorage.getItem.
Re: Trying to retrieve a session variable in Javascript?
Keep in mind that localStorage and sessionStorage are two different things. Just make sure that you're using the right storage.
Re: Trying to retrieve a session variable in Javascript?
I know that localStorage will retain the value on your drive unless you clear it out afterward...which I am.