当某些操作设置cookie时,让我的页面显示cookie信息

时间:2017-06-17 12:05:22

标签: javascript cookies

有没有办法让我的页面使用Javascript实时监控cookie,如果设置了cookie,那么它会发送警报吗?

我不明白的部分是如何实时检查cookie?例如,用户可能会单击一个复选框,将设置一个cookie,然后将页面设置为"请参阅"现在已经设置了cookie并触发警报,所有这些都是实时的。

以下是一个示例(未正确编写),它显示了我的目标。

<div id="click" onclick="setcookie()"></div>

<script>
function checkcookie() {
if (cookie_exists)
alert('cookie exists')
}
</script>

我不明白的部分是如何让checkcookie()函数持续监控我刚刚点击设置的cookie的存在?

3 个答案:

答案 0 :(得分:0)

以下是编写和阅读Cookie的基本功能:

  function setCookie(cname, cvalue, exdays) {
   var d = new Date();
   d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
   var expires = 'expires=' + d.toUTCString();
   document.cookie = cname + '=' + cvalue + ';' + expires + '';
   path = '/';
}
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 null;
}
function checkCookie(cname) {
  var cookie = getCookie(cname);
  if (cookie != null) {
    return true;
  } else {
    return false;
  }
}

function remove_cookie(cname) {
    document.cookie = cname + '=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/;'
}

来自w3schools.com/js/js_cookies.asp

答案 1 :(得分:0)

唯一的方法是使用

window.setInterval("CheckCookie()", 1000);

每秒检查一次cookie

答案 2 :(得分:0)

您必须实施间隔超时以持续检查cookie的值。

 function getCookie(name) {
     var dc = document.cookie;
     var prefix = name + "=";
     var begin = dc.indexOf("; " + prefix);
     if (begin == -1) {
         begin = dc.indexOf(prefix);
         if (begin != 0) return null;
     }
     else
     {
         begin += 2;
         var end = document.cookie.indexOf(";", begin);
         if (end == -1) {
         end = dc.length;
         }
     }
     // because unescape has been deprecated, replaced with decodeURI
     //return unescape(dc.substring(begin + prefix.length, end));
     return decodeURI(dc.substring(begin + prefix.length, end));
 } 

 // Method used for continuously monitoring a cookie
 function monitorCookie(cookieName) {
     setInterval(function() {
         var cookieValue = getCookie(cookieName);

         console.log('Yummy Cookie =' + cookieValue);
     }, 500);// monitor cookie every 500 miliseconds.
 }

 $(document).ready(function() {
     monitorCookie("YummyCookie");
 });