How to perform function once per visitor after loading the site?

1

How to make JavaScript run only once per visitor (type if already registered in the browser's cokkies, do not run anymore).

<?php
     $tmp='<script>
     Push.create("Olá Mundo!", {
                      body: "Esta é uma mensagem nova",
                      icon: "images/logo.jpg",
                      timeout: 4000,
                      onClick: function() {
                               window.location="http://www.google.com.br";
                               this.close();
                      }
                  });
            </script>';

            echo $tmp;
?>
    
asked by anonymous 22.08.2017 / 02:21

3 answers

1

You are using PHP because it does not create and check the cookie with PHP. Then it only gives echo $tmp; if the cookie does not exist or has expired

<?php
$tmp='<script>
    Push.create("Olá Mundo!", {
        body: "Esta é uma mensagem nova",
        icon: "images/logo.jpg",
        timeout: 4000,
        onClick: function() {
            window.location="http://www.google.com.br";
            this.close();
        }
    });
</script>';


$biscoito=$_COOKIE[acessada];

if(empty($biscoito)){

   setcookie( "acessada", "sim", strtotime( '+1 days' ), '/' );  // 24 horas

    echo $tmp;

}
?>

cookies - php

empty -php

    
22.08.2017 / 03:07
0

I would do it using the new localStorage of HTML 5, it's very simple and I believe that all modern browsers already have:

<script>
// escrevendo
localStorage.setItem("ja_acessou", "Sim");
</script>

<script>
// Lendo
if (localStorage.ja_acessou) console.log('já acessou!');
</script>

Example number of hits:

<script>
if (localStorage.qt_acessos) localStorage.qt_acessos += 1;
else localStorage.qt_acessos = 1;

</script>
    
22.08.2017 / 02:58
0

I particularly like using cookies for this case, for example:

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function showUmaVesPorDia() {
    var cooki = getCookie("msgCookie");
    if (cooki != "") {
        // ja existe o cookie msgCookie!
    } else {
           // não existe, vamos guardar!
           $("#mensagem").fadeIn('slow');       
           setCookie("msgCookie", 1, 1);
    }
}
$(document).ready(function(){
        showUmaVesPorDia() ;
});

Here's a working example link

    
22.08.2017 / 11:45