Reputation: 458
I'm trying to share some information between browser windows/tabs, and I'm leery of HTML5 local storage because of browser support issues. Some googling lead me to believe cookies can be used for this, so I grabbed jquery.cookie and set up a simple test.
Two pages which write a cookie when loaded:
$.cookie("testValue", new Date().getTime());
and a button that displays the cookie value in an alert on each:
alert($.cookie("testValue"));
When testing, I see different values on each page, which would lead me to believe this just doesn't work, but I keep running across posts here and elsewhere where people seem to be recommending it, so I'm wondering if I'm just doing something wrong?
Upvotes: 0
Views: 5597
Reputation: 324630
Attempt number two =P
Try something like this:
<iframe id="cookies" src="refresher.html" style="display: none"; />
<script type="text/javascript">
(function() {
var ifr = document.getElementById('cookies');
setInterval(function() {
var cd = ifr.contentDocument.cookie.split(";");
l = cd.length, i, k, ret = {};
for( i=0; i<l; i++) {
k = cd[i].split("=");
k[0] = k[0].replace(/^ +| +$/g,'');
k[1] = k[1].replace(/^ +| +$/g,'');
ret[k[0]] = k[1];
}
window.cookiedata = ret;
},5000);
})();
</script>
refresher.html:
<script type="text/javascript">setTimeout(function() {location.reload();},5000);</script>
You can still use jQuery $.cookie
to set a cookie, but to get them you now use cookiedata.cookiename
.
Adjust the 5000
to whatever seems a good compromise between responsiveness and reloading data.
Upvotes: 0
Reputation: 4291
DateTime()
is not defined. Use Date()
instead.
$.cookie("testValue", new Date().getTime());
Anyway, it works for me. Here's a simple html page:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>demo</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.js'></script>
<script type='text/javascript' src="https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js"></script>
<script type='text/javascript'>
$(window).load(function(){
$("#get").click(function(){
alert($.cookie("testValue"));
});
$("#set").click(function(){
$.cookie("testValue", new Date().getTime());
});
});
</script>
</head>
<body>
<a id="get" href="#">get cookie</a>
<a id="set" href="#">set cookie</a>
</body>
</html>
Tried in localhost using FireFox 10.0.
Upvotes: 0
Reputation: 324630
Cookies are only updated in the JavaScript environment when set by JS, or when the page loads.
localStorage was designed for this. IE8 supports it just fine, it's only the really old IE7 and below that don't. Although IE9 is Windows-Vista-and-7-only, IE8 is fine on XP so you should have no troubles asking your users who are still on archaic browsers to update.
(I can't say this enough, but IE really need an auto-updater like all other browsers...)
Upvotes: 2