Document cookie Property - Javascript DOM

Javascript examples for DOM:Document cookie

Description

The cookie property sets or gets all name/value pairs of cookies in the current document.

Set the cookie property with the following Values

Parameter Description
newCookie A String that sets a semicolon-separated list of name=value pairs, or one name=value pair together with any of the following, optional, values:
  • expires=date - Optional. Sets the date in GMT format. If not specified, the cookie is deleted when the browser is closed
  • path=absolute path - Optional. If not specified, the cookie belongs to the current page
  • domain=domainname - Optional. 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=your name; expires=Thu, 18 Dec 2020 12:00:00 UTC; path=/";

To use commas, semicolons or whitespaces, encode them with encodeURIComponent() method

Return Value

A String, containing the name/value pairs of cookies in the document

The following code shows how to get the cookies associated with the current document:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">Test</button>

<p id="demo"></p>

<script>
function myFunction() {/*from w  w  w  .  j  ava  2s . c o m*/
    var x = document.cookie;
    document.getElementById("demo").innerHTML = "Cookies associated with this document: " + x;
}
</script>

</body>
</html>

Related Tutorials