美文网首页
浏览器跨标签页通信

浏览器跨标签页通信

作者: sunflower_07 | 来源:发表于2023-07-11 11:38 被阅读0次

定义:

BroadcastChannel,就字面意思来言,叫做“广播频道”,官方文档说,该API是用于同源不同页面之间完成通信的功能;

image.png

1. BroadcastChannel

js复制代码// 新建实例
const bc = new BroadcastChannel('broad-test');
// 监听消息
bc.onmessage = function(e) {
  console.log('接收到消息', JSON.stringify(e.data))
}
// 发送消息
bc.postMessage({name: 'lalalalal----'})

2. WebWorker

js复制代码// 主线程代码
//创建实例
const worker = new Worker('swScript.js', {scope: './'});
// 监听
worker.onmessage = function (event) {
      console.log('Received message ' , event.data);
}
// 发送消息
worker.postMessage({method: 'echo', args: ['Work']});

//  worker 线程:swScript.js 文件 监听并转发
console.log('webworker', this)
const self = this;
self.addEventListener('message', function (e) {
    console.log('service worker receive message', e, e.data);
    self.postMessage(e.data);
});

3. 本地存储

js复制代码// 可监听同源 storage 改变
window.addEventListener('storage', function (e) {
   console.log('e', e)
});
window.localStorage.setItem('test', Math.random())

注意
在一个页面内修改 storage,当前页面是监听不到的;
若后面 set 的值与之前相同,是不会触发监听事件的。

4. postmessage

4.1 window.open

js复制代码// 监听        
window.addEventListener('message', function (e) {
            alert(JSON.stringify(e.data));
        });
// 打开新页面
newPage = window.open('http://localhost:3000/pagetalk');
// 发送消息
function sendMessage() {
    if(!newPage.closed) {
        // 要在哪个页面接收,就用哪个 window 来 postMessage
        newPage.postMessage({name: 'lalalalal----'});
    }
}    

4.2 iframe

iframe内,脚本可以通过 window.parent 引用父窗口对象。父窗口也可通过 window.frames 获取嵌套的内容。
可实现跨源通信:通过 e.origin 校验发送源来进行安全验证;

浏览器支持

image.png

相关文章

网友评论

      本文标题:浏览器跨标签页通信

      本文链接:https://www.haomeiwen.com/subject/ctnyudtx.html