Does anyone know is it possible to assign an object into cookies in javascript? If yes, how can we do it?
Serializing Javascript Objects into Cookies
var expires = new Date();
expires.setDate(expires.getDate() + 7); // 7 = days to expire
document.cookie = "logintoken=somelogintoken;expires=" + expires.toGMTString();
Read JavaScript Cookies also.
Cookies store only string values so you need to serialize your object to string somehow. And deserialize it when you will read it from the cookie. However this can work only if your object has some simple data (strings, numbers, arrays), and will not work with functions for sure. I'm also not sure why you want to do that.
You will need to serialize your object and then write it out as text. I would consider using JSON as it's well supported.
There is a good parser here. You will just need to call the JSON.stringify() method. To write cookies in javascript you need to append a string in the correct format to
window.document.cookie
The string should be in the following format
'name=cookiename; expires=Thu, 2 Aug 2001 20:47:11 UTC; path=/'
Cookies are designed to only hold text, so if you need serialize your object into a simple string for this to work.
On most browsers cookies are limited to +- 4096 bytes so you can't store much information.
If you can serialize your object into its canonical string representation, and can unserialize it back into its object form from said string representation, then yes you can put it into a cookie.
Judging from your earlier question regarding storing the result of window.open()
into a cookie, this is not the answer you are hoping for.
This is one way to do it,
- Serialize your object into JSON.
- Base64 encode the JSON.
- Use the Base64 encoded string as the cookie value.
Just reverse the process when reading the cookie.
You have to use Version 1 cookies because Base64 character sets needs to be quoted. If you want use old Netscape style cookie, you need to use an URL-safe Base64 encoder.
Of course, this is only good for small objects.