最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Threeway cookie - Stack Overflow

programmeradmin0浏览0评论

I'm building a popup with 3 buttons! Each button needs to set a cookie but with different expiry time/date. I'm using jquery.cookie for this!

  • 1 button is more a session cookie. So when clicking this button the popup needs to dissapear and shown again when I start a new browser screen. So NOT when I open a page in the same browser window and same website.

  • 1 button is for "Don't show popup again" which will set cookie to 7 days

  • 1 cookie is set in the AJAX succes function and is set to 365 days

I'm having trouble to get the different expiry times to set up correctly. So for example when I click the button with the session cookie then the popup shows again when I open a new page inside the website.

I can't see what I'm doing wrong! I don't get any console errors but the cookies just won't set properly.

What I have is this:

 $(document).ready(function(){


    var my_cookie = $.cookie('regNewsletter');

    if (!my_cookie) {
      setTimeout(function(){
        $('#newsletter').modal('show');
      }, 1000);
    }
    $(".close--btn").on("click", function () {
      $.cookie('regNewsletter', true, {
        path: '/',
        domain: ''
      });
    });
    $(".dismiss--btn").on("click", function () {
      $.cookie('regNewsletter', true, {
        path: '/',
        domain: '',
        expires: 7
      });
    });
    console.log(my_cookie);

 // code for removing cookie when session ends //
 window.onbeforeunload = function() {
    $.removeCookie('regNewsletter', { path: '/', domain: '' });
 };


 $("#newsletter .btn").click(function(e){
      e.preventDefault();

       $.ajax({
       ... 

        success: function(txt, status, xhr){
       // some code //

              $.cookie('regNewsletter', true, {
                path: '/',
                expires: 365
              });

        // etc etc //


  });

I'm building a popup with 3 buttons! Each button needs to set a cookie but with different expiry time/date. I'm using jquery.cookie for this!

  • 1 button is more a session cookie. So when clicking this button the popup needs to dissapear and shown again when I start a new browser screen. So NOT when I open a page in the same browser window and same website.

  • 1 button is for "Don't show popup again" which will set cookie to 7 days

  • 1 cookie is set in the AJAX succes function and is set to 365 days

I'm having trouble to get the different expiry times to set up correctly. So for example when I click the button with the session cookie then the popup shows again when I open a new page inside the website.

I can't see what I'm doing wrong! I don't get any console errors but the cookies just won't set properly.

What I have is this:

 $(document).ready(function(){


    var my_cookie = $.cookie('regNewsletter');

    if (!my_cookie) {
      setTimeout(function(){
        $('#newsletter').modal('show');
      }, 1000);
    }
    $(".close--btn").on("click", function () {
      $.cookie('regNewsletter', true, {
        path: '/',
        domain: ''
      });
    });
    $(".dismiss--btn").on("click", function () {
      $.cookie('regNewsletter', true, {
        path: '/',
        domain: '',
        expires: 7
      });
    });
    console.log(my_cookie);

 // code for removing cookie when session ends //
 window.onbeforeunload = function() {
    $.removeCookie('regNewsletter', { path: '/', domain: '' });
 };


 $("#newsletter .btn").click(function(e){
      e.preventDefault();

       $.ajax({
       ... 

        success: function(txt, status, xhr){
       // some code //

              $.cookie('regNewsletter', true, {
                path: '/',
                expires: 365
              });

        // etc etc //


  });
Share Improve this question asked Jan 26, 2016 at 18:04 MeulesMeules 1,3895 gold badges26 silver badges74 bronze badges 0
Add a ment  | 

5 Answers 5

Reset to default 4 +100

To set a session cookie you don't need to delete it onbeforeunload, but just set a cookie with no expiry set. You also don't need to set the domain, if the default is OK, which is the domain of the current webpage.

live demo

$(document).ready(function(){
    var my_cookie = $.cookie('regNewsletter');        
    if (my_cookie && my_cookie=="true") {
      alert("Cookie found");
    } else {
      setTimeout(function(){
        //$('#newsletter').modal('show');
        alert("Popup newsletter");
      }, 1000);
    }
    $(".close--btn").on("click", function () {
      // set a session cookie. It'll be automatically deleted
      // when the browser is closed
      $.cookie('regNewsletter', 'true', {
        path: '/'
      });
      alert("session cookie set");
    });
    $(".dismiss--btn").on("click", function () {
      $.cookie('regNewsletter', 'true', {
        path: '/',
        expires: 7
      });
      alert("cookie set for 7 days");
    });
    console.log(my_cookie);
    $("#newsletter .btn").click(function(e){
       e.preventDefault();
       $.ajax({
         url:"setcookie.html",
         success: function(txt, status, xhr){
           $.cookie('regNewsletter', 'true', {
             path: '/',
             expires: 365
           });
           alert("cookie set for 365 days");
         }
       });
     });
 });

html:

<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="jquery.cookie.js"></script>
<button class="close--btn">close</button>
<button class="dismiss--btn">dismiss</button>
<span id="newsletter"><button class="btn">ajax</button></span>

Why do you have this piece of code?

// code for removing cookie when session ends //
window.onbeforeunload = function() {
   $.removeCookie('regNewsletter', { path: '/', domain: '' });
};

It is not clear from your question which circumstances are causing the problems you are seeing, but I suspect this is part, if not all, of them.

The point of a session cookie is that it will be deleted automatically when the browser closes. There is no need to manually remove it.

That piece of code will remove your cookie as soon as you close the tab, window, or navigate to another page though. So if you are doing any of those then reopening the page within the same browser session you will get the behaviour you are seeing, as the cookie no longer exists.

Obviously the 7 and 365 day expirations are also ignored for the same reason.

Remove the piece of code and the cookie should then persist for the appropriate length

You can check your cookies using browser developer tools. In Google Chrome, it is F12 -> Resources at the top (of the newly opened frame), Cookies on the left.

I think the problem might be that you don't set the correct domain for these cookies.

Update: Another suspicious thing is that you remove the cookie on window unolad:

window.onbeforeunload = function() {
    $.removeCookie('regNewsletter', { path: '/', domain: '' });
};

You can set it to 7 or 365 days, but it gets removed on window unload, because you don't have 3 cookies here, it is the same cookie 'regNewsletter' which is configured with different parameters.

Each time you set it, it overwrites previous values (this is probably what you want). But it looks like you should not remove it.

Update 2: instead of removing it, try to just leave it without the expiration date, according to this question and answer it should be automatically cleared when users closes the browser. According to your description, it should be even better than removing it in onbeforeunload.

Your code has only a few issues:

  • You can use the default value for the domain
  • You don't need the onbeforeunload method to remove the session cookie
  • There is no need to setup listeners if the cookie is present

var my_cookie = $.cookie('regNewsletter');

if (!my_cookie) {

  setTimeout(function() {
    $('#newsletter').modal('show');
  }, 1000);

  // 365 days cookie

  $("#newsletter .btn").click(function(e) {
    e.preventDefault();
    $.cookie('regNewsletter', true, {
      path: '/',
      expires: 365
    });
  });

  // Session cookie

  $(".close--btn").on("click", function() {
    $.cookie('regNewsletter', true, {
      path: '/'
    });
  });

  // 7 days cookie

  $(".dismiss--btn").on("click", function() {
    $.cookie('regNewsletter', true, {
      path: '/',
      expires: 7
    });
  });
}

jquery-cookie : No longer maintained, superseded by JS Cookie: https://github./js-cookie/js-cookie

Try the below using js-cookie

$(document).ready(function(){

    var my_cookie = Cookies.get('regNewsletter');

    if (!my_cookie) {
      setTimeout(function(){
      //  $('#newsletter').modal('show');
      }, 1000);
    }
    $(".close--btn").on("click", function () {
        Cookies.set('regNewsletter', true, { path: '' });
    });
    $(".dismiss--btn").on("click", function () {
        Cookies.set('regNewsletter', true, { expires: 7, path: '' });
    });
    //console.log(my_cookie);


 $("#newsletter .btn").click(function(e){
      e.preventDefault();
        $.ajax({
          method: "POST",
          url: ".....",
          data: YourData
        }).done(function( msg ) {
            Cookies.set('regNewsletter', true, { expires: 365, path: '' });
          });

    });

});
发布评论

评论列表(0)

  1. 暂无评论