Can't see localstorage event across tabs

雨燕双飞 提交于 2019-12-20 02:58:12

问题


I'm trying to create a simple proof-of-concept regarding the use of localStorage to trigger tabs in my application when changes occur. I know this is possible based on other articles I've seen. I understand the spec states the event will fire on ever page except the one I'm on - this is in fact what I want. However, I can't seem to get this simple demo to actually work.

I've taken the code below, and opened up multiple tabs of it. Using my Chrome Dev Tools, I can check >localStorage in the console and see the value before and after the "Add" and "Clear" buttons are pressed - they are in fact functioning as desired in storing and clearing the key value pair into local storage, yet the event isn't firing the alert.

I even placed breakpoints in the javascript in my Chrome Dev Tools of each tab, yet I can never seem to get the "onStorageEvent" function to hit in any tab opened.

What am I doing wrong?

<!DOCTYPE html>
<html>

<head>
  <title>Tab1</title>
</head>

<body>
  <button id="add" onclick="localStorage.setItem('tab','changed')">Add</button>
  <button id="clear" onclick="localStorage.clear()">Clear</button>
  <script type="text/javascript">
    function onStorageEvent() {
      alert("storage event: " + localStorage.getItem("tab"));
    }

    window.addEventListener('storage', onStorageEvent, false);
  </script>
</body>

</html>

回答1:


In order for the window.addEventListener to work on storage:

  1. you MUST access the page using web-server (http://a.b.c.d/ or http://domain)

    • Direct access (using file:/// or c:\file.html will not work.
      (chrome and ie ignore it, firefox and safari can run it anyway).
  2. I would consider also removing the 3rd, it is not relevant to elements in your DOM tree, and it might cause troubles (let the browser have it's defaults).

This code was tested in Chrome 52, Firefox 47+48, IE 11, Safari 5.7.1

<!DOCTYPE html>
<html>

<head>
  <title>Tab1</title>
</head>

<body>
  <button id="add" onclick="localStorage.setItem('tab','changed')">Add</button>
  <button id="clear" onclick="localStorage.clear()">Clear</button>
  <script type="text/javascript">
    function onStorageEvent() {
      alert("storage event: " + localStorage.getItem("tab"));
    }

    window.addEventListener('storage', onStorageEvent);
  </script>
</body>

</html>


来源:https://stackoverflow.com/questions/38962045/cant-see-localstorage-event-across-tabs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!