107

I was wondering if it's possible to create session only cookies with Javascript. When the browser is closed the cookies should be removed.

I can't use anything on the server as the website is HTML only ... so no server side script is used.

I read something about this here: http://blog.lysender.com/2011/08/setting-session-only-cookie-via-javascript/ but i can't find any more information about this ... so i was wondering if this method is reliable.

4 Answers 4

166

Yes, that is correct.

Not putting an expires part in will create a session cookie, whether it is created in JavaScript or on the server.

See https://stackoverflow.com/a/532660/1901857

For the use case in the question (no server side code), sessionStorage is a simpler solution. But sessionStorage is client only, so would not work if you need to access the stored value on the server (e.g. user logins etc.)

4
  • It does not work for me and tried in many ways... Maybe this answer is outdated.
    – Dan
    May 15, 2020 at 14:16
  • 1
    @Dan Session cookies doesn't work in case of enabled config: "Continue where you left off" in browser. In that cases browsers will not destroy session cookies after closing. Jun 16, 2020 at 14:21
  • @TaronSaribekyan you are right but you have to ask all the users of your website to disable the config "Continue where you left off". Instead sessionStorage worked straight away in all the browsers.
    – Dan
    Jun 18, 2020 at 8:18
  • 1
    @Rhumborl also, sessionstorage is limited to the current tab, whereas a session cookie is valid for the whole browser session
    – muzzletov
    Sep 29, 2022 at 8:50
54

A simpler solution would be to use sessionStorage, in this case:

var myVariable = "Hello World";

sessionStorage['myvariable'] = myVariable;

var readValue = sessionStorage['myvariable'];
console.log(readValue);

However, keep in mind that sessionStorage saves everything as a string, so when working with arrays / objects, you can use JSON to store them:

var myVariable = {a:[1,2,3,4], b:"some text"};

sessionStorage['myvariable'] = JSON.stringify(myVariable);
var readValue = JSON.parse(sessionStorage['myvariable']);

A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated.

So, when you close the page / tab, the data is lost.

13
  • 1
    Yes, Session storage is the best choice for this use casE. Jan 7, 2013 at 13:13
  • 19
    actually now i am using session storage ... but apparently when you open a new tab in chrome and firefox you can't access the stuff you stored in the session storage ... so that's why i was looking at session cookies: code.google.com/p/chromium/issues/detail?id=165452
    – Daan Poron
    Jan 7, 2013 at 13:19
  • In that case, the cookies should be reliable, although I have no idea how well-supported they are.
    – Cerbrus
    Jan 7, 2013 at 13:26
  • 2
    Session (and Local) storage are affected by Same-Origin-Policy, so if you switch from http to https, you do not have access to the stuff stored in http (and visa-versa) Apr 14, 2014 at 20:15
  • 4
    I think SessionStorage only provides a client-only solution without any access to these values on server-side. In many server-side frameworks like ASP.Net and PHP, we would like to easily access the client-side values that we may have stored without using hidden fields etc., and then cookies become a better solution since cookies get automatically sent to the server-side.
    – Sunil
    Nov 6, 2015 at 17:09
10

For creating session only cookie with java script, you can use the following. This works for me.

document.cookie = "cookiename=value; expires=0; path=/";

then get cookie value as following

 //get cookie 
var cookiename = getCookie("cookiename");
if (cookiename == "value") {
    //write your script
}

//function getCookie        
function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
    }
    return "";
}

Okay to support IE we can leave "expires" completely and can use this

document.cookie = "mtracker=somevalue; path=/";
2
  • 4
    expires=0 in IE doesn't set a cookie at all: blog.lysender.com/2011/08/…
    – JDandChips
    Nov 5, 2014 at 12:44
  • 1
    expires="" works in IE, and allows you to reset the expiry of a cookie to Session, if you have explictly set it
    – koolunix
    Mar 2, 2017 at 23:49
-1

Use the below code for a setup session cookie, it will work until browser close. (make sure not close tab)

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
  }
  function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') {
        c = c.substring(1);
      }
      if (c.indexOf(name) == 0) {
        return c.substring(name.length, c.length);
      }
    }
    return false;
  }
  
  
  if(getCookie("KoiMilGaya")) {
    //alert('found'); 
    // Cookie found. Display any text like repeat user. // reload, other page visit, close tab and open again.. 
  } else {
    //alert('nothing');
    // Display popup or anthing here. it shows on first visit only.  
    // this will load again when user closer browser and open again. 
    setCookie('KoiMilGaya','1');
  }
1
  • No, setting an expire date is what not makes it a browser session cookie
    – tim
    Aug 21, 2021 at 11:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.