How To Set And Retrieve Cookie Values Using JavaScript
Cookies are a great way to store data or information in a browser. They are are arbitrary pieces of data, usually chosen and first sent by the web server, and stored on the client computer by the web browser. You can read more about it here Wikipedia.
Cookies can be accessed by navigating to the storage tab in your browser’s inspect window.
Find Cookies Storage
- Right-click on any part of the browser to reveal a fly-out menu then click on Inspect.
- Or use CTRL +SHIFT+ I keys on your keyboard.
- Or press F12 on your keyboard to Open the Browser’s console.
In some browsers you might find it in the storage Tab, other browsers (like chrome), you will find it in Application Tab.
HOW DO I CREATE COOKIES ?
You can create cookies by using this simple JavaScript code. In your Browser console copy & paste this code.
Now use the Enter Key on your keyboard to run the code.
You’ll notice that nothing visually happened! Check your browser’s storage for cookies and you’ll find the cookie there!
Now cookies take their Domain name from where their value was created. If you run the code on a localhost domain, you will find the cookie under localhost domain.
You have successfully created a cookie but how do I access my cookie value?
HOW DO I ACCESS COOKIES?
Now Depending on the cookie you wish to access its value, you must use a JavaScript function that searches through your browser’s cookies and brings out the particular one you’re looking for. Luckily for us, there’s a code for this!
Now call the function getCookie(name), and pass the name of the Cookie as an argument.
Meanwhile,
You can retrieve all stored cookies in your Browser by running this simple code.
This will return all stored cookies for that particular Domain.
You can read more here W3Schools