Session only cookies with Javascript

后端 未结 4 1419
感动是毒
感动是毒 2020-11-28 07:48

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

4条回答
  •  旧巷少年郎
    2020-11-28 08:18

    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.

提交回复
热议问题