如何使用jQuery绑定到所有浏览器的localStorage更改事件? [英] How to bind to localStorage change event using jQuery for all browsers?

查看:169
本文介绍了如何使用jQuery绑定到所有浏览器的localStorage更改事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b

  $(function(){$ b)如何将函数绑定到使用jQuery的HTML5 localStorage更改事件? 
$ b $(window).bind('storage',function(e){
alert('storage changed');
});

localStorage .setItem('a','test');

});

我已经尝试了上述方法,但没有显示提醒。



更新:它适用于Firefox 3.6,但它在Chrome 8或IE 8中不起作用,所以问题应该更多'如何使用jQuery绑定到localStorage更改事件所有浏览器?'

解决方案

事实证明,这实际上工作正常,我误解了规范


在与本地存储区关联的存储对象x上​​调用setItem(),removeItem()和clear()方法时,如果方法执行了某些操作,则每个Document对象的Window对象localStorage属性的Storage对象与x以外的存储区相关联,必须触发存储事件。

换句话说,申通快递对于更新 localStorage 对象并导致事件的窗口/选项卡,每个窗口/选项卡都会触发暴怒事件。



因此,该事件并未被解雇,因为我只打开了一个窗口/选项卡。如果我将上面的代码放在页面中并在两个选项卡中打开页面,我会在第二个选项卡中看到事件触发。

/stackoverflow.com/questions/4679023/bug-with-chromes-localstorage-implementation/4679754#4679754\">这个问题的答案包含更多细节。


How do I bind a function to the HTML5 localStorage change event using jQuery?

$(function () {

  $(window).bind('storage', function (e) {
    alert('storage changed');
  });

  localStorage.setItem('a', 'test');

});

I've tried the above but the alert is not showing.

Update: It works in Firefox 3.6 but it doesn't work in Chrome 8 or IE 8 so the question should be more 'How to bind to localStorage change event using jQuery for all browsers?'

解决方案

It turns out that this is actually working correctly and I have misinterpreted the specification

When the setItem(), removeItem(), and clear() methods are called on a Storage object x that is associated with a local storage area, if the methods did something, then in every Document object whose Window object's localStorage attribute's Storage object is associated with the same storage area, other than x, a storage event must be fired

In other words, a storage event is fired on every window/tab except for the one that updated the localStorage object and caused the event.

So the event was not fired because I only had one window/tab open. If I place the above code in a page and open the page in two tabs I would see the event fired in the second tab.

This answer on the problem contains more details.

这篇关于如何使用jQuery绑定到所有浏览器的localStorage更改事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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