一个组件中:
import React, { useRef, useEffect } from 'react';
export default function Acompo() {
const channelRef = useRef<BroadcastChannel | null>(null);
useEffect(() => {
if (!channelRef.current) {
channelRef.current = new BroadcastChannel('proxy-channel');
channelRef.current.onmessage = event => {
console.log('Received message:', event.data);
};
}
return () => {
channelRef.current?.close();
};
}, []);
return (
<div>
<button>Send Message134</button>
</div>
);
}
另一个组件中:
const sendMessage = () => {
const channel = new BroadcastChannel('proxy-channel');
channel.postMessage('Hello from this tab!');
};