Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Cookies!!!🍪</title>
- </head>
- <body>
- <button type="button" onclick="addCookie()">Dodaj plik cookie</button>
- <button type="button" onclick="showCookies()">Pokaż pliki cookies</button>
- <button type="button" onclick="updateCounter()">Zwiększ licznik</button>
- <h1 id="licznik"></h1>
- <script>
- function addCookie() {
- document.cookie = "licznik=99;expires=Wed, 18 Dec 2030 12:00:00 GMT";
- }
- function showCookies() {
- alert(document.cookie)
- }
- // Ustawia cookie o danej nazwie, wartości i okresie ważności (dni)
- function setCookie(name, value, days) {
- let expires = "";
- if (days) {
- const date = new Date();
- date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
- expires = "; expires=" + date.toUTCString();
- }
- document.cookie = name + "=" + encodeURIComponent(value) + expires + "; path=/";
- }
- // Odczytuje cookie o podanej nazwie; zwraca wartość lub null
- function getCookie(name) {
- const nameEQ = name + "=";
- const ca = document.cookie.split(";");
- for (let c of ca) {
- c = c.trim();
- if (c.indexOf(nameEQ) === 0) {
- return decodeURIComponent(c.substring(nameEQ.length));
- }
- }
- return null;
- }
- // Aktualizuje (lub inicjuje) cookie "licznik" i wyświetla je w <span id="licznik">
- function updateCounter() {
- let count = getCookie("licznik");
- if (count === null) {
- count = 1; // pierwsza wizyta
- } else {
- count = parseInt(count, 10) + 1;
- }
- setCookie("licznik", count, 7); // cookie ważne 7 dni
- document.getElementById("licznik").textContent = count;
- }
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement