简体   繁体   中英

Sharing Cookie among browser tabs without refreshing tab in javascript

hi i am designing a real estate website and i have many ads in it i add an option to every of my ads and if user click on "add to favorites" that ad's id and url saves in a cookie and retrieve in "favorite page" thus user can review that certain ad every time he or she wants. each of my ads have a address like this localhost/viewmore.php?ID=a number
totally saving process in cookie works fine but recently i realized something. consider i visit one of my ads with this address localhost/viewmore.php?ID=10 and click on "add to favorite" then if i open another page with this address localhost/viewmore.php?ID=8 and then i read my cookie in "favorite page" i will see this result
[{"favoriteid":"10","url":"http://localhost/viewcookie.php?ID=10"},{"favoriteid":"8","url":"http://localhost/viewcookie.php?ID=8"}]
which is perfectly true and it is what i expect.

the problem

now consider unlike the previous case i open both of ads and then click on "add to favorite" on first ad and then go to second ad (without any refreshing) and click on "add to favorite" on second ad this time if i read my cookie in "favorite page" i will see this result
[{"favoriteid":"8","url":"http://localhost/viewcookie.php?ID=8"}]
which is not true i want two see both of ad's id and url in my cookie not just last one.
ps: i use push() method to add new object to cookie array i think i have to update it every time after click? any idea thanks

 /* * Create cookie with name and value. * In your case the value will be a json array. */ function createCookie(name, value, days) { var expires = '', date = new Date(); if (days) { date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = '; expires=' + date.toGMTString(); } document.cookie = name + '=' + value + expires + '; path=/'; } /* * Read cookie by name. * In your case the return value will be a json array with list of pages saved. */ function readCookie(name) { var nameEQ = name + '=', allCookies = document.cookie.split(';'), i, cookie; for (i = 0; i < allCookies.length; i += 1) { cookie = allCookies[i]; while (cookie.charAt(0) === ' ') { cookie = cookie.substring(1, cookie.length); } if (cookie.indexOf(nameEQ) === 0) { return cookie.substring(nameEQ.length, cookie.length); } } return null; } function eraseCookie(name) { createCookie(name,"",-1); } var faves = new Array(); function isAlready(){ var is = false; $.each(faves,function(index,value){ if(this.url == window.location.href){ console.log(index); faves.splice(index,1); is = true; } }); return is; } $(function(){ var url = window.location.href; // current page url var favID; var query = window.location.search.substring(1); var vars = query.split("&"); for (var i=0;i<vars.length;i++) { var pair = vars[i].split("="); var favID = (pair[0]=='ID' ? pair[1] :1) //alert(favID); } // this is the part i think i have to update every time without refreshing******************************* $(document.body).on('click','#addTofav',function(e){ e.preventDefault(); if(isAlready()){ } else { var fav = {'favoriteid':favID,'url':url}; faves.push(fav); } //******************************************************************************************************* var stringified = JSON.stringify(faves); createCookie('favespages', stringified); }); var myfaves = JSON.parse(readCookie('favespages')); if(myfaves){ faves = myfaves; } else { faves = new Array(); } }); 

Your problem is that you are looking at variable faves , which is initialized at document load, but it isn't being updated as cookie changes.

The second page looks at the variable, sees no favorites from first page, because it doesn't actually look at cookie.

Then, it just resets the cookie with it's values.

Here is the full code, with added functionality from chat:

/* 
 * Create cookie with name and value. 
 * In your case the value will be a json array. 
 */
function createCookie(name, value, days) {
  var expires = '',
    date = new Date();
  if (days) {
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = '; expires=' + date.toGMTString();
  }
  document.cookie = name + '=' + value + expires + '; path=/';
}
/* 
 * Read cookie by name. 
 * In your case the return value will be a json array with list of pages saved. 
 */
function readCookie(name) {
  var nameEQ = name + '=',
    allCookies = document.cookie.split(';'),
    i,
    cookie;
  for (i = 0; i < allCookies.length; i += 1) {
    cookie = allCookies[i];
    while (cookie.charAt(0) === ' ') {
      cookie = cookie.substring(1, cookie.length);
    }
    if (cookie.indexOf(nameEQ) === 0) {
      return cookie.substring(nameEQ.length, cookie.length);
    }
  }
  return null;
}
/* 
 * Erase cookie with name. 
 * You can also erase/delete the cookie with name. 
 */
function eraseCookie(name) {
  createCookie(name, '', -1);
}

var faves = {
  add: function (new_obj) {
    var old_array = faves.get();

    old_array.push(new_obj);
    faves.create(old_array);
  },

  remove_index: function (index) {
    var old_array = faves.get();

    old_array.splice(index, 1);
    faves.create(old_array);
  },

  remove_id: function (id) {
    var old_array = faves.get();

    var id_index = faves.get_id_index(id);
    faves.remove_index(id_index);
  },

  create: function (arr) {
    var stringified = JSON.stringify(arr);
    createCookie('favespages', stringified);
  },

  get: function () {
    return JSON.parse(readCookie('favespages')) || [];
  },

  get_id_index: function (id) {
    var old_array = faves.get();

    var id_index = -1;
    $.each(old_array, function (index, val) {
      if (val.id == id) {
        id_index = index;
      }
    });

    return id_index;
  },

  update_list: function () {
    $("#appendfavs").empty();
    $.each(faves.get(), function (index, value) {
      var element = '<li class="' + index + '"><h4>' + value.id + '</h4> <a href="' + value.url + '">Open page</a> ' +
        '<a href="javascript:void(0);" class="remove" data-id="' + value.id + '">Remove me</a>';

      $('#appendfavs').append(element);
    });
  }
}

$(function () {
  var url = window.location.href;

  $(document.body).on('click', '#addTofav', function (e) {
    var pageId = window.location.search.match(/ID=(\d+)/)[1];

    if (faves.get_id_index(pageId) !== -1) {
      faves.remove_id(pageId);
    }
    else {
      faves.add({
        id: pageId,
        url: url
      });
    }

    faves.update_list();
  });

  $(document.body).on('click', '.remove', function () {
    var url = $(this).data('id');

    faves.remove_id(url);
    faves.update_list();
  });

  $(window).on('focus', function () {
    faves.update_list();
  });

  faves.update_list();
});

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