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?
Here is the example from w3chools that was mentioned.
I have written simple cookieUtils, it has three functions for creating the cookie, reading the cookie and deleting the cookie.
For those who need save objects like {foo: 'bar'}, I share my edited version of @KevinBurke's answer. I've added JSON.stringify and JSON.parse, that's all.
So, now you can do things like this:
I've used accepted answer of this thread many times already. It's great piece of code: Simple and usable. But I usually use babel and ES6 and modules, so if you are like me, here is code to copy for faster developing with ES6
Accepted answer rewritten as module with ES6:
And after this you can simply import it as any module (path of course may vary):
A cheeky and simple way of reading a cookie could be something like:
This could be used if you know your cookie contains something like:
username="John Doe"; id=123;
. Note that a string would need quotes in the cookie. Not the recommended way probably, but works for testing/learning.