How do I create and read a value from cookie in JavaScript?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
ES7, using a regex for get(). Based on MDN
Usage - Cookie.get(name, value [, options]):
options supports all standard cookie options and adds "days":
Alternative ways of setting expiration:
Current date can be gotten with: new Date(Date.now()).toUTCString()
Other answers use "expires" instead of "max-age" to support older IE versions. This method requires ES7, so IE7 is out anyways (this is not a big deal).
Note: Funny characters such as "=" and "{:}" are supported as cookie values, and the regex handles leading and trailing whitespace (from other libs).
If you would like to store objects, either encode them before and after with and JSON.stringify and JSON.parse, edit the above, or add another method. Eg:
Mozilla provides a simple framework for reading and writing cookies with full unicode support along with examples of how to use it.
Once included on the page, you can set a cookie:
read a cookie:
or delete a cookie:
For example:
See more examples and details on Mozilla's document.cookie page.
I use this object. Values are encoded, so it's necessary to consider it when reading or writing from server side.
JQuery Cookies
or plain Javascript:
Here's a code to Get, Set and Delete Cookie in JavaScript.
Source: http://mycodingtricks.com/snippets/javascript/javascript-cookies/
I've used js-cookie to success.