简体   繁体   中英

Jquery cookie not working across a wordpress site

I have used jquery cookie for my Wordpress site. Cookie is set when site is loaded. Expiration period of cookie is set as 1 minute. I need the cookie value to get expired if a visitor visits the site for more than 1 minute. Currently, cookie value is getting set whenever visitor navigate through the pages.

$(document).ready(function(){
    var date = new Date();
    date.setTime(date.getTime() + (60 * 1000));
    $.cookie('timeset', '1', { expires: date, path: '/' ,domain  : 'example.com'});
    setInterval(function(){ 
        console.log($.cookie('timeset'));               
    }, 1000);
});

You can use sessionStorage and conditionally set the cookie. You can update your function as follows.

Updated function

$(document).ready(function(){
    var date = new Date();
    date.setTime(date.getTime() + (60 * 1000));
    if(sessionStorage.getItem('cookie_timeset') == null){
        $.cookie('timeset', '1', { expires: date, path: '/' ,domain  : 'example.com'});
        sessionStorage.setItem('cookie_timeset', true);
    }
    setInterval(function(){ 
        console.log($.cookie('timeset'));               
    }, 1000);
});

For the very first time, value of the sessionStorage key cookie_timeset will be null . Thus fulfilling the if condition cookie will be set.

During any further or other page loads (user navigates through website) value of the sessionStorage key cookie_timeset will be true , thus if condition will be skipped and cookie will not be set.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM