Sometimes, we want to save session only cookies with JavaScript.
In this article, we’ll look at how to save session only cookies with JavaScript.
How to save session only cookies with JavaScript?
To save session only cookies with JavaScript, we can use session storage instead of cookies.
For instance, we write
const myVariable = { a: [1, 2, 3, 4], b: "some text" };
sessionStorage["myVariable"] = JSON.stringify(myVariable);
const readValue = JSON.parse(sessionStorage["myVariable"]);
to save an entry with key myVariable into session storage with
sessionStorage["myVariable"] = JSON.stringify(myVariable);
Since myVariable is an object, we’ve convert it to a string with JSON.stringify before we can save the value.
Then we read the value by the key with
sessionStorage["myVariable"]
Then we call JSON.parse to parse the stringified JSON object into a JavaScript object.
Conclusion
To save session only cookies with JavaScript, we can use session storage instead of cookies.