jquery - 如何为所有浏览器使用 jQuery 绑定(bind)到 localStorage 更改事件?

标签 jquery html google-chrome

如何使用 jQuery 将函数绑定(bind)到 HTML5 localStorage 更改事件?

$(function () {

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

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

});

我已尝试上述方法,但未显示警报。

更新:它在 Firefox 3.6 中有效,但在 Chrome 8 或 IE 8 中无效,因此问题应该更多“如何使用 jQuery 为所有浏览器绑定(bind)到 localStorage 更改事件?”

最佳答案

事实证明,这实际上工作正常,我误解了 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

换句话说,除了更新 localStorage 对象并引发事件的窗口/选项卡外,每个窗口/选项卡都会触发一个存储事件。

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

This answer on the problem 包含更多详细信息。

关于jquery - 如何为所有浏览器使用 jQuery 绑定(bind)到 localStorage 更改事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4671852/

相关文章:

javascript - jQuery - 如何在条件为真时取消表单提交以防止默认

javascript - 使用 html 中名称为 ="example"的值

php - 基于selectbox ajax php mysql填充文本框

html - 具有多个 parent 和不同线型的家谱

php - 保护服务器上的一个特定文件; .htaccess 有什么好办法吗?

javascript - 为什么在附加到 DOM 时要连接 HTML 标签

javascript - 改变元素的宽度?

selenium - 错误号 : 33: SessionNotCreatedError session not created exception from unknown error while trying to simulate chrome browser using SeleniumBasic

google-chrome - 无法使用经过 http 基本身份验证的 Selenium WebDriver 中的默认/自定义配置文件启动 Google Chrome

c# - UI 自动化的 Google Chrome 可访问树缓存问题