javascript – How and where should I put the parameters for cookies?

Question:

Hello, I am trying to create the code that controls the validity time of a session, so that the browser remembers the web and does not have to load it every time I reload it, but I did not give that in a course that I did. I have looked for information about it and with the code that it creates I see that the browser does not remember the web. I have read something about the expires and max-age parameters, but I don't know how or where to put them. I show what I have achieved so far, but that it does not do the function I expected for the browser to remember my website. If you can help me, is there somewhere I can find a way to learn how to write the code and where to put it, or explain how I should proceed. They also suggested that I look for documentation of localStorage is native JS, but I have searched and with what I saw, I am not able to create the code to get browsers to remember the web. The thing is that it takes a long time to load, and I already corrected the errors that it had to be slow. And no matter how much I open it over and over again, it shows me the cookie message again and loads everything again. Thank you.

function getCookie(c_name) {
      var c_value = document.cookie;
      var c_start = c_value.indexOf(" " + c_name + "=");
      if (c_start == -1) {
        c_start = c_value.indexOf(c_name + "=");
      }
      if (c_start == -1) {
        c_value = null;
      } else {
        c_start = c_value.indexOf("=", c_start) + 1;
        var c_end = c_value.indexOf(";", c_start);
        if (c_end == -1) {
          c_end = c_value.length;
        }
        c_value = unescape(c_value.substring(c_start, c_end));
      }
      return c_value;
    }

    function setCookie(c_name, value, exdays) {
      var exdate = new Date();
      exdate.setDate(exdate.getDate() + exdays);
      var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
      document.cookie = c_name + "=" + c_value;
    }

    if (getCookie('tiendaaviso') != "1") {
      document.getElementById("cookies").style.display = "block";
    }
    function PonerCookie() {
      setCookie('tiendaaviso', '1', 365);
      document.getElementById("cookies").style.display = "none";
    }
#cookies {
	background-color: #333;
	display:none;
	position:fixed;
	left:0px;
	right:0px;
	bottom:0px;
	padding-bottom:60px;
	width:100%;
	text-align:center;
	min-height:40px;
	background-color: rgba(0, 0, 0, 0.5);
	color:#fff;
	z-index:99999;
}

.inner {
	width:100%;
	position:absolute;
	padding-left:5px;
	font-family:verdana;
	font-size:12px;
	top:30%;
}

.inner a.ok {padding:4px;color:#00ff2e;text-decoration:none;}
.inner a.info {padding-left:5px;text-decoration:none;color:#faff00;}
<!DOCTYPE html>
<html lang="es">

<head>
<title>cokies</title>
</head>
<body>
  <div id="cookies">
    <div class="inner">
      Esta web utiliza cookies como datos estad&iacute;sticos de su navegaci&oacute;
      Si contin&uacute;a navegando consideramos que acepta el uso de cookies.
      <a href="javascript:void(0);" class="ok" onclick="PonerCookie();">
        <b>OK</b>
      </a> |
      <a href="politica-cookies.html" target="_blank" class="info">M&aacute;s informaci&oacute;n</a>
    </div>
  </div>
  </body>
  </html>

Answer:

The code provided is functional as long as the javascript loads or executes it after the "cookies" div is created otherwise the line

document.getElementById("cookies").style.display = "block";

will give an error because the element with ID "cookies" does not exist yet in the DOM

For managing cookies, the functions you use are fine, for greater compatibility I suggest the Mozilla library that you can find here: https://github.com/madmurphy/cookies.js

The expires parameter is being set by the setCookie function (it takes a number of days and adds them to the current date)

function setCookie(c_name, value, exdays) {

in summary the code should look like this:

<!DOCTYPE html>
<html lang="es">
<head>
<title>cokies</title>
<style>
#cookies {
    background-color: #333;
    display:none;
    position:fixed;
    left:0px;
    right:0px;
    bottom:0px;
    padding-bottom:60px;
    width:100%;
    text-align:center;
    min-height:40px;
    background-color: rgba(0, 0, 0, 0.5);
    color:#fff;
    z-index:99999;
}

.inner {
    width:100%;
    position:absolute;
    padding-left:5px;
    font-family:verdana;
    font-size:12px;
    top:30%;
}

.inner a.ok {padding:4px;color:#00ff2e;text-decoration:none;}
.inner a.info {padding-left:5px;text-decoration:none;color:#faff00;}
</style>
</head>
<body>
  <div id="cookies">
   <div class="inner">
  Esta web utiliza cookies como datos estad&iacute;sticos de su navegaci&oacute;
  Si contin&uacute;a navegando consideramos que acepta el uso de cookies.
  <a href="javascript:void(0);" class="ok" onclick="PonerCookie();">
    <b>OK</b>
  </a> |
  <a href="politica-cookies.html" target="_blank" class="info">M&aacute;s informaci&oacute;n</a>
</div>
</div>
</body>
<script>
function getCookie(c_name) {
  var c_value = document.cookie;
  var c_start = c_value.indexOf(" " + c_name + "=");
  if (c_start == -1) {
    c_start = c_value.indexOf(c_name + "=");
  }
  if (c_start == -1) {
    c_value = null;
  } else {
    c_start = c_value.indexOf("=", c_start) + 1;
    var c_end = c_value.indexOf(";", c_start);
    if (c_end == -1) {
      c_end = c_value.length;
    }
    c_value = unescape(c_value.substring(c_start, c_end));
  }
  return c_value;
}

function setCookie(c_name, value, exdays) {
  var exdate = new Date();
  exdate.setDate(exdate.getDate() + exdays);
  var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
  document.cookie = c_name + "=" + c_value;
}

if (getCookie('tiendaaviso') != "1") {
  document.getElementById("cookies").style.display = "block";
}
function PonerCookie() {
  setCookie('tiendaaviso', '1', 365);
  document.getElementById("cookies").style.display = "none";
}
</script>
</html>

Note that the javascript is being loaded after it appears

<div id="cookies"> 

in the html.

Edit: How to add the cookie notice to my website.

(or how to break everything in 3 steps if I don't copy the files)

To add this code to your website, you must first find out what the main page file is. The most common names are (ordered from most common to rarest):

  • index.html
  • index.htm
  • index.php
  • default.html
  • default.htm
  • index.shtml
  • index.php5
  • index.php4
  • index.php3
  • index.cgi
  • home.html
  • home.htm
  • Index.html
  • Index.htm
  • Index.shtml
  • Index.php
  • Index.cgi
  • Default.html
  • Default.htm
  • Home.html
  • Home.htm
  • placeholder.html

Note: on some servers, the first letter in uppercase is important, that is why some appear repeated.

Once the file is located, you have to:

  • download it
  • make a copy in case we get mixed up and everything breaks
  • open it in a text editor

… and look for the line where it says:

</head>

that can be close to or attached to the line that says

<body>

Now well above </head> and without replacing anything that already exists

You paste this part of the code:

<style>
#cookies {
    background-color: #333;
    display:none;
    position:fixed;
    left:0px;
    right:0px;
    bottom:0px;
    padding-bottom:60px;
    width:100%;
    text-align:center;
    min-height:40px;
    background-color: rgba(0, 0, 0, 0.5);
    color:#fff;
    z-index:99999;
}

.inner {
    width:100%;
    position:absolute;
    padding-left:5px;
    font-family:verdana;
    font-size:12px;
    top:30%;
}

.inner a.ok {padding:4px;color:#00ff2e;text-decoration:none;}
.inner a.info {padding-left:5px;text-decoration:none;color:#faff00;}
</style>

Then you look for a line that says:

</body>

Note: it is usually at the end of the file

Here we are going to add a first part above and another below

A above

<div id="cookies">
   <div class="inner">
  Esta web utiliza cookies como datos estad&iacute;sticos de su navegaci&oacute;
  Si contin&uacute;a navegando consideramos que acepta el uso de cookies.
  <a href="javascript:void(0);" class="ok" onclick="PonerCookie();">
    <b>OK</b>
  </a> |
  <a href="politica-cookies.html" 
     target="_blank" class="info">M&aacute;s informaci&oacute;n</a>
 </div>
 </div>

B Below:

<script>
function getCookie(c_name) {
  var c_value = document.cookie;
  var c_start = c_value.indexOf(" " + c_name + "=");
  if (c_start == -1) {
    c_start = c_value.indexOf(c_name + "=");
  }
  if (c_start == -1) {
    c_value = null;
  } else {
    c_start = c_value.indexOf("=", c_start) + 1;
    var c_end = c_value.indexOf(";", c_start);
    if (c_end == -1) {
      c_end = c_value.length;
    }
    c_value = unescape(c_value.substring(c_start, c_end));
  }
  return c_value;
}

function setCookie(c_name, value, exdays) {
  var exdate = new Date();
  exdate.setDate(exdate.getDate() + exdays);
  var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
  document.cookie = c_name + "=" + c_value;
}

if (getCookie('tiendaaviso') != "1") {
  document.getElementById("cookies").style.display = "block";
}
function PonerCookie() {
  setCookie('tiendaaviso', '1', 365);
  document.getElementById("cookies").style.display = "none";
}
</script>
Scroll to Top