Jin Yong
Jin Yong

Reputation: 43778

can we assign object into cookie in javascript?

Does anyone know is it possible to assign an object into cookies in javascript? If yes, how can we do it?

Upvotes: 2

Views: 5956

Answers (7)

ZZ Coder
ZZ Coder

Reputation: 75456

This is one way to do it,

  1. Serialize your object into JSON.
  2. Base64 encode the JSON.
  3. 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.

Upvotes: 3

rahul
rahul

Reputation: 187030

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.

Upvotes: 0

Crescent Fresh
Crescent Fresh

Reputation: 116980

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.

Upvotes: 6

Geoff Appleford
Geoff Appleford

Reputation: 18832

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.

Upvotes: 0

Alex
Alex

Reputation: 36576

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=/'

Upvotes: 1

RaYell
RaYell

Reputation: 70414

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.

Upvotes: 0

Biju CD
Biju CD

Reputation: 5109

i think only 4kb is allowd to a cookie

Upvotes: -2

Related Questions