Do you know about cookies?

Asked

Viewed 328 times

-4

I was looking for more knowledge about cookies on youtube and only found video in English, but what’s the big deal? I don’t speak English! However I was able to understand that cookies work in this way stored, read and sometimes deleted.

What am I getting at? Well... I want to put cookies in 2 scripts, but so far can not. I had asked here on the forum how to put cookies in this script

<a id="id1" href="https://br.answers.yahoo.com" onclick="myFunction(event)" target="_blank">Clique Aqui</a> <br/><br/>

<script language="javascript">
    function myFunction(s) {
        var id = s.target.id;

        document.getElementById(id).style.color = "green";
        setTimeout(function(){
            document.getElementById(id).style.color = "blue";
        }, 10000);
    }
</script>

Then I got this reply:

If you want it to continue indefinitely until you delete it, you can do this with Html5, or if you want it to forget the data when closing the browser as well.

INDEFINIDAMENTE: // Armazenar

localStorage.setItem("lastname", "Smith");
// Receber

var lastname = localStorage.getItem("lastname");
// Remover

localStorage.removeItem("lastname");
TEMPORARIAMENTE // Armazenar

sessionStorage.setItem("lastname", "Smith");
// Receber

var lastname = sessionStorage.getItem("lastname");
// Remover

sessionStorage.removeItem("lastname");

But I do not understand how to insert, has how to help me?

2 answers

2

I’m not sure what values you want to store in cookies. But here are some features that are handy for working with customer-side cookies:

Activate cookie:

// entra como argumentos: o nome que quer dar ao cookie, respetivo valor, e número de dias para ficar ativo
function set_cookie(nome, valor, dias) {

    //data em que o cookie vai expirar, ficar desativo
    expires = new Date(new Date().getTime() + parseInt(dias) * 1000 * 60 * 60 * 24);

    // set cookie
    document.cookie = name+'='+value+'; expires=' +expires+ '; path=/';

}

Check whether there is:

// aqui entra o nome do cookie que quer e respetivo valor, vai-lhe ser returnado true (existe, já está ativo) ou false (não existe)
function cookie_exists(nome,valor) {

    var cookie = document.cookie; // Aqui vamos buscar todos os cookies do nosso site

    var cookieNameValue = cookie.split(";"); // vamos dividir a string por ';', para obtermos um array (vetor) com todos os nome/valores dos cookies
    var countCookies = cookieNameValue.length;
    var cookieWeWant = nome+"="+valor; // este é o cookie que queremos

    for(var i=0; i<countCookies; i++) {
        if(cookieWeWant == cookieNameValue[i].trim()) {
            return true;
        }
    }

    return false;
}

Delete a cookie:

// aqui entra o nome do cookie que quer apagar
function delete_cookie(nome) {
    //para apagar um cookie basta ativar um cookie para uma data passada
    expires = new Date(new Date().getTime() - 1);
    document.cookie = nome+'=123; expires=' +expires+ '; path=/';
}

1


Javascript Cookie

There is a very detailed api for working with Cookies through Javascript, in an easy and well documented way.

Follows: https://github.com/js-cookie/js-cookie

Import:

<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.1.1/js.cookie.min.js"></script>

Gets and Set Cookies:

Create a cookie that expires 7 days from now, valid throughout the site:

Cookies.set('name', 'value', { expires: 7 });

Read the Cookie:

Cookies.get('name');

Read all visible cookies

Cookies.get();

Delete cookie:

Cookies.remove('name');

In the documentation of github there are more detailed examples.

  • Thanks man I’ll try to understand more

  • @Marcio.Sx Solved your problem?

  • Partly because at first I wanted it ready, but it was better because I learned!

  • @Marcio.Sx If some of the answers solved your problem, it would be interesting to accept one of them.

  • how do I do that?

  • @Marcio.Sx Below the numbering of the votes, a "little old" appears. There you can click and accept one of the answers.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.