實現同一頁面多tab時的狀態同步
- 2019 年 12 月 26 日
- 筆記
不同tab的js執行環境是不同的,因此變數不會共享,watcher也不會互相影響。
可以利用 storage事件監控localstorge的變化 ,storege事件只能註冊在window上
創建兩個頁面 A和B 分別在不同的Tab打開
<!DOCTYPE html> <html> <head lang="en"> <title>A</title> </head> <body> <script> window.addEventListener("storage", function (e) { alert(e.newValue); }); </script> </body> </html><!DOCTYPE html> <html> <head lang="en"> <title>B</title> </head> <body> <script> localStorage.clear(); localStorage.setItem('foo', 'bar'); </script> </body> </html>

