切记,需要以下2点:

1、 localStorage发生变化,初次设置值不生效。

2、不同的浏览器tab,本页面不生效。比如打开了a.html和b.html,a.html设置了一个值,b.html去修改值,事件才会生效

3、在中间件下测试,比如tomcat,nginx

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        function save() {
            localStorage.setItem("change-event", new Date().getTime())
        }
        function change() {
            localStorage.setItem("change-event",new Date().getTime())
        }	
		
        window.onstorage = function (e) {
            console.log(e)
            console.log(`The ${e.key} key has been changed from ${e.oldValue} to ${e.newValue}.`);
        };		
    </script>
</head>

<body>
    <button onclick="save()">localstorge click</button>
	<br>
	<iframe src="./b.html">
	</iframe>
	
</body>

</html>

 解决同一个页面下的瓶颈,使用iframe

通知仅在不同的上下文中接收。这意味着不同的页面,不要期望在同一页面中不同对象的上下文中使用本地存储进行通信。一些浏览器会考虑将“同一页面”应用于当前页面内的不同 iframe。Chrome 和 Firefox 的行为似乎符合预期,您可以在同一页面中的不同 iframe 之间进行通信,但为​​了更好地使用发布消息,请尽可能使用。

 

 

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐