在浏览器标签之间共享Cookie,而无需刷新javascript中的标签 [英] Sharing Cookie among browser tabs without refreshing tab in javascript

查看:37
本文介绍了在浏览器标签之间共享Cookie,而无需刷新javascript中的标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在设计一个房地产网站,并且其中有很多广告,因此我为每个广告都添加了一个选项,如果用户单击添加到收藏夹" ,则该广告的ID和网址会保存在Cookie中检索并在收藏夹页面" 中检索,因此用户可以在每次需要时查看该广告.我的每个广告都有一个这样的地址 localhost/viewmore.php?ID =一个数字
完全保存cookie的过程效果很好,但是最近我意识到了.考虑我访问此地址为 localhost/viewmore.php?ID = 10 的广告,然后单击添加至收藏夹" ,然后如果我打开另一个具有此地址的页面 localhost/viewmore.php?ID = 8 ,然后我在收藏夹页面" 中读取cookie,我会看到此结果
[{"favoriteid":"10","url":"http://localhost/viewcookie.php?ID = 10"},{"favoriteid":"8","url":"http://localhost/viewcookie.php?ID=8}]
完全正确,这正是我的期望.

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.

现在考虑不像以前的情况,我打开两个广告,然后在第一个广告上单击添加到收藏夹" ,然后转到第二个广告(不刷新),然后单击如果我在收藏夹页面" 中读取了Cookie,则这一次在第二个广告上添加到收藏夹" ,我将看到此结果
[{"favoriteid":"8","url":"http://localhost/viewcookie.php?ID = 8"}]
这是不正确的,我想让两个人在Cookie中看到广告的ID和网址,而不仅仅是最后一个.
ps:我使用push()方法将新对象添加到cookie数组中,我认为每次单击后都必须对其进行更新?任何想法谢谢

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();
    }

});

推荐答案

您的问题是您正在查看变量 faves ,该变量在文档加载时初始化,但是没有更新为Cookie更改.

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.

第二页查看变量,而第一页则没有收藏夹,因为它实际上并未查看cookie.

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

然后,它只是使用其值重置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();
});

这篇关于在浏览器标签之间共享Cookie,而无需刷新javascript中的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆