var allcookies = document.cookie; document.write ("All Cookies : " + allcookies );
In the syntax, by using the ‘document.cookie’ method we can get all the cookies of the document and store them in a variable. As we have above seen the expire attribute is an option and if the user does not define the time or date for expiring for them, then it will always be called.
First, we will create a form in the body of the code to define some input fields in the body.
In the form using the button tag, we will create a button, in which we will define the onclick event.
The onclick event leads to invoking the function that is defined in it when the button is pressed.
In the script, we will define the function in which first by using the ‘document.write’ method we will get all the cookies of the page in a variable and later print them.
By using the split() method, we call store all the cookies in the separate indexes of an array.
We will traverse the array and for each index, we can get the name and value of the current cookie and can print it separately.
In this example, we will get all the cookies of the document and print them all together first then we will print all of them separately.
In the above code, first, we have created a form in the body of the code using the <form> tag, in which we have created a button that will call a function defined in the script of the code.
In the script, we have defined the ‘ReadCookie’ function in which we have defined a variable allcookies which will contain all the cookies of the document and that will get using the document.cookie() method.
Further, we have contained all the cookies separated in an array using the split function and later printed each of them differently. For printing them separately we traversed over the array and at each iteration printed the value and the name.
Note − Cookies have a shelf life. When the browser is closed, a cookie that has no defined expiration date will also be deleted. Because they are deleted after the browser session is over, they are sometimes referred to as session cookies (when the browser is closed). The browser will delete cookies having an expired date in the past. Setting an expiration date and storing it in the cookie will extend its lifespan past the current browser session. You may achieve this by entering a date and time in the "expires" property.
- Related Articles
- How to create an Android notification with expiration date?
- How long can we use food items after expiration date?
- How to set a cookie to a specific domain in selenium webdriver with Python?
- How to check if a cookie is set in Laravel?