Jquery cookie监视器

编程入门 行业动态 更新时间:2024-10-22 16:51:37
本文介绍了Jquery cookie监视器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

当cookie被更改时,什么是最好的JS或JQuery特定方法来监控浏览器的网页生命周期中的Cookie生命周期?

What's the best JS or JQuery-specific approach to monitor a cookie through-out the page life on the browser and trigger an event, when the cookie is' changed?

推荐答案

据我所知,不可能直接将更改(或类似)事件绑定到cookie。相反,我会采用这种方法:

As far as I know, it is not possible to bind a change (or similar) event to a cookie directly. Instead, I would go for this approach:

创建一个轮询器,每隔X毫秒将Cookie值与之前已知的值进行比较。 p>

Create a poller that compares the cookie value to the previously known value every X milliseconds.

// basic functions from the excellent www.quirksmode/js/cookies.html function readCookie(name) { var nameEQ = name + "="; 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,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } ///////////////////////////////// // ACTUAL FUN STUFF BELOW ///////////////////////////////// var cookieRegistry = []; function listenCookieChange(cookieName, callback) { setInterval(function() { if (cookieRegistry[cookieName]) { if (readCookie(cookieName) != cookieRegistry[cookieName]) { // update registry so we dont get triggered again cookieRegistry[cookieName] = readCookie(cookieName); return callback(); } } else { cookieRegistry[cookieName] = readCookie(cookieName); } }, 100); }

用法如下:

listenCookieChange('foo', function() { alert('cookie foo has changed!'); });

注意:这没有经过测试,只是一个简短的演示问题。

Note: this has not been tested and is just a quick demo of how I would approach the problem.

编辑:我已经测试了这个现在,它的工作原理。 查看示例:)

更多推荐

Jquery cookie监视器

本文发布于:2023-11-11 06:14:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1577599.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:监视器   Jquery   cookie

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!