-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #815 from ndw/cookies
Another interactive example
- Loading branch information
Showing
2 changed files
with
67 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
<!DOCTYPE html> | ||
<html xmlns='http://www.w3.org/1999/xhtml'> | ||
<head> | ||
<meta charset='UTF-8'/> | ||
<title>Cookies</title> | ||
</head> | ||
<body> | ||
<h1>Cookies</h1> | ||
|
||
<p id="message">I have no cookies.</p> | ||
|
||
<p> | ||
<button id="hobnail">Hobnail</button> | ||
<button id="chocchip">Chocolate chip</button> | ||
<button id="sugar">Sugar</button> | ||
</p> | ||
|
||
<div id="cookies"></div> | ||
|
||
</body> | ||
<script src="js/cookies.js"></script> | ||
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
(function() { | ||
counter = 0; | ||
|
||
function showCookies() { | ||
const div = document.querySelector("#cookies"); | ||
let count = 0 | ||
let inner = "<table><thead><tr><th>Name</th><th>Value</th></tr></thead>" | ||
inner += "<tbody>"; | ||
document.cookie.split("; ").forEach(cookie => { | ||
if (cookie.startsWith("cookie") || cookie.startsWith("selenium")) { | ||
count++; | ||
tokens = cookie.split("=") | ||
inner += `<tr><td>${tokens[0]}</td><td>${tokens[1]}</td></tr>` | ||
} | ||
}); | ||
if (count == 0) { | ||
div.innerHTML = ""; | ||
} else { | ||
div.innerHTML = `${inner}</tbody></table>` | ||
} | ||
} | ||
|
||
function setCookie(name, value, seconds) { | ||
var expires = ""; | ||
if (seconds) { | ||
var date = new Date(); | ||
date.setTime(date.getTime() + (seconds*1000)); | ||
expires = "; expires=" + date.toUTCString(); | ||
} | ||
document.cookie = name + "=" + (value || "") + expires + "; SameSite=Strict; path=/"; | ||
} | ||
|
||
function setupButton(id) { | ||
let button = document.querySelector(`#${id}`); | ||
button.addEventListener("click", (event) => { | ||
setCookie(`cookie${++counter}`, button.innerHTML, 5) | ||
showCookies() | ||
}); | ||
} | ||
|
||
setupButton("hobnail") | ||
setupButton("chocchip") | ||
setupButton("sugar") | ||
showCookies() | ||
})(); |