Get the cookies associated with the current document:
var x = document.cookie;
Click the button to get the cookies associated with the current document.
<!DOCTYPE html> <html> <body> <button onclick="myFunction()">Test</button> <p id="demo"></p> <script> function myFunction() {/*www .j a va 2 s. c o m*/ var x = document.cookie; document.getElementById("demo").innerHTML = "Cookies associated with this document: " + x; } </script> </body> </html>
The cookie property sets or gets all name/value pairs of cookies in the current document.
Cookie format:
A String that specifies a semicolon-separated list of name=value pairs together with any of the following optional values:
Field | Optional | Description |
---|---|---|
expires=date | Optional | the date in GMT format. If not specified, the cookie is deleted when the browser is closed |
path=path | Optional | the directory of the cookie, (e.g., '/', '/dir'). The path must be absolute. If not specified, the cookie belongs to the current page |
domain=domainname | Optional | the domain of the site (e.g., 'example.com', '.example.com', 'sub-domain.example.com'). If not specified, the domain of the current document will be used |
secure | Optional | use a secure protocol (https) for sending the cookie to the server |
An example of creating a cookie:
document.cookie="username=java2s.com; expires=Thu, 25 Dec 2022 12:00:00 UTC; path=/";
The value of a cookie cannot contain commas, semicolons or white spaces.
You can use the encodeURIComponent()
method to encode.
The cookie property returns a String containing the name/value pairs of cookies in the document.