Advertisement
gandalfbialy

Untitled

May 30th, 2025
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html lang="en">
  3.  
  4. <head>
  5. <meta charset="UTF-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Cookies!!!🍪</title>
  8. </head>
  9.  
  10. <body>
  11. <button type="button" onclick="addCookie()">Dodaj plik cookie</button>
  12.  
  13. <button type="button" onclick="showCookies()">Pokaż pliki cookies</button>
  14.  
  15. <button type="button" onclick="updateCounter()">Zwiększ licznik</button>
  16.  
  17. <h1 id="licznik"></h1>
  18.  
  19. <script>
  20. function addCookie() {
  21. document.cookie = "licznik=99;expires=Wed, 18 Dec 2030 12:00:00 GMT";
  22. }
  23.  
  24. function showCookies() {
  25. alert(document.cookie)
  26. }
  27.  
  28. // Ustawia cookie o danej nazwie, wartości i okresie ważności (dni)
  29. function setCookie(name, value, days) {
  30. let expires = "";
  31. if (days) {
  32. const date = new Date();
  33. date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
  34. expires = "; expires=" + date.toUTCString();
  35. }
  36. document.cookie = name + "=" + encodeURIComponent(value) + expires + "; path=/";
  37. }
  38.  
  39. // Odczytuje cookie o podanej nazwie; zwraca wartość lub null
  40. function getCookie(name) {
  41. const nameEQ = name + "=";
  42. const ca = document.cookie.split(";");
  43. for (let c of ca) {
  44. c = c.trim();
  45. if (c.indexOf(nameEQ) === 0) {
  46. return decodeURIComponent(c.substring(nameEQ.length));
  47. }
  48. }
  49. return null;
  50. }
  51.  
  52. // Aktualizuje (lub inicjuje) cookie "licznik" i wyświetla je w <span id="licznik">
  53. function updateCounter() {
  54. let count = getCookie("licznik");
  55. if (count === null) {
  56. count = 1; // pierwsza wizyta
  57. } else {
  58. count = parseInt(count, 10) + 1;
  59. }
  60. setCookie("licznik", count, 7); // cookie ważne 7 dni
  61. document.getElementById("licznik").textContent = count;
  62. }
  63. </script>
  64. </body>
  65.  
  66. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement