zh-rocco / fe-notes

:memo: 前端笔记

Home Page:https://zh-rocco.github.io/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

【JS】前端跨页面通信

zh-rocco opened this issue · comments

commented

localStorage

具体方案

// A.html
localStorage.setItem('message', 'hello');

// B.html
window.onstorage = e => {
  // e.key, e.oldValue, e.newValue
};

tips

  1. 触发写入操作的页面下的 storage listener 不会被触发
  2. storage 事件只有在发生改变的时候才会触发,即重复设置相同值不会触发 listener
  3. safari 隐身模式下无法设置 localStorage 值

优劣

API 简单直观,兼容性好,除了跨域场景下需要配合其他方案,无其他缺点

BroadcastChannel

具体方案

localStorage 方案基本一致,需要额外初始化

// A.html
const channel = new BroadcastChannel('tabs');
channel.onmessage = e => {
  // e.data
};

// B.html
const channel = new BroadcastChannel('tabs');
channel.postMessage('hello');

优劣

localStorage 方案没特别区别,都是同域、API 简单,BroadcastChannel 方案兼容性差些(chrome > 58),但比 localStorage 方案生命周期短(不会持久化),相对干净些。

参考