[javascript] Setting session variable using javascript

I am getting name and email id of a user after he logs in via facebook to my website.. I want to add those variables in session on login form itself using javascript; I tried following:

FB.api('/me', function(me) {
        if (me.name) {
            document.getElementById('auth-displayname').innerHTML = me.name; <% Session["fbName"] = me.name; %>
        }
}

it gives error like me (in this line: <%Session["fbName"] = me.name; %>) does not exist in the current context etc.. my div "auth-displayname" is getting that value but I'm having problem with session variable

How can I do this

This question is related to javascript session-variables

The answer is


You can use

sessionStorage.SessionName = "SessionData" ,

sessionStorage.getItem("SessionName") and

sessionStorage.setItem("SessionName","SessionData");

See the supported browsers on http://caniuse.com/namevalue-storage


A session is stored server side, you can't modify it with JavaScript. Sessions may contain sensitive data.

You can modify cookies using document.cookie.

You can easily find many examples how to modify cookies.


It is very important to understand both sessionStorage and localStorage as they both have different uses:

From MDN:

All of your web storage data is contained within two object-like structures inside the browser: sessionStorage and localStorage. The first one persists data for as long as the browser is open (the data is lost when the browser is closed) and the second one persists data even after the browser is closed and then opened again.

sessionStorage - Saves data until the browser is closed, the data is deleted when the tab/browser is closed.

localStorage - Saves data "forever" even after the browser is closed BUT you shouldn't count on the data you store to be there later, the data might get deleted by the browser at any time because of pretty much anything, or deleted by the user, best practice would be to validate that the data is there first, and continue the rest if it is there. (or set it up again if its not there)

To understand more, read here: localStorage | sessionStorage


You could better use the localStorage of the web browser.

You can find a reference here