浏览器页签间通信

50 阅读1分钟

1. localStorage 事件监听

  • 只有同源页面才能互相通信
// 发送消息的页签
localStorage.setItem('message', JSON.stringify({
  type: 'my-message',
  data: 'Hello from Tab 1!',
  timestamp: Date.now()
}));


// 接收消息的页签
window.addEventListener('storage', (event) => {
  if (event.key === 'message') { // localStorage key
    const message = JSON.parse(event.newValue);
    if (message.type === 'my-message') { // 不同的消息类型
      console.log('Received:', message.data);
    }
  }
});

2. Broadcast Channel API

  • hooks
// src/hooks/useBroadcastChannel.js

// 一个应用可以使用同一个channelName,然后根据不同的消息类型type,进行区分拾取
export const useBroadcastChannel = (channelName = 'message') => {
  const channel = new BroadcastChannel(channelName);

  // 发送消息
  const postMessage = ({ type, content }) => {
    channel.postMessage({
      type,
      content,
    });
  };

  // 接收消息
  const onmessage = (cb) => {
    channel.onmessage = (event) => {
      cb(event.data);  
    };
  };

  return {
    postMessage,
    onmessage,
  };
};

  • 发送消息
import { useBroadcastChannel } from '@/hooks/useBroadcastChannel'
import { reactive } from 'vue'

const { postMessage } = useBroadcastChannel()

const user = reactive({
  name: 'bwf',
  age: 18
})
postMessage({
    type: "message-user",
    content: {...user}
})

postMessage({
    type: "message-token",
    content: '321123'
})
  • 接受消息
import {useBroadcastChannel} from '@/hooks/useBroadcastChannel'

const { onmessage } = useBroadcastChannel()

onmessage((data)=>{
  console.log('onmessage---data', data); // { type: 'message-token', content: '321123' }
})