Aymen Kareem Aymen Kareem - 1 month ago 15
Javascript Question

session and cookies in javascript

I have the following code:

<html>
<body>
<form action="second.html" onsubmit="return myFunction();">
Enter a session variable: <input id="sess" type="text" />
</br>
Enter a coockie variable: <input id="cookiess" type="text" />

</br>
<input type="submit" />
</form>

<script>
function myFunction() {
document.cookie = "username="+document.getElementById("cookiess").value + "; expires=Fri, 14 Oct 2016 12:00:00 UTC";
sessionStorage["myKey"] = document.getElementById("sess").value;

return true;
}

</script>
</body>
</html>


and this is the second.html page:

<html>
<body>

<script>

alert(sessionStorage["myKey"] + document.cookie);
</script>
</body>
</html>


I am not getting both the session and the cookie variable in the second page. Just an empty alert. Why?

Answer

Hi if you want to check how session storage works you can see the below code... its for a single page.

if 2 pages are there If you're just running this from a file:// protocol, it won't work

  <!DOCTYPE html>
<html>
<head>
<script>
function clickCounter() {
    if(typeof(Storage) !== "undefined") {
        if (sessionStorage.clickcount) {
            sessionStorage.clickcount = Number(sessionStorage.clickcount)+1;
           sessionStorage["myKey"] = sessionStorage.clickcount;
        } else {
            sessionStorage.clickcount = 1;
        }
        document.getElementById("result").innerHTML = "You have clicked the button " + sessionStorage.clickcount + " time(s) in this session."+sessionStorage["myKey"];
    } else {
        document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
    }
}
</script>
</head>
<body>
<p><button onclick="clickCounter()" type="button">Click me!</button></p>
<div id="result"></div>
<p>Click the button to see the counter increase.</p>
<p>Close the browser tab (or window), and try again, and the counter is reset.</p>
</body>
</html>