浏览器插件在content_script和top窗口之间进行消息通信

为什么要进行消息通信?

        content_script和top窗口之间除了DOM共享之外,window对象是不共享的。如果content_script需要获得top窗口中window对象的数据,就需要使用到通信。反之,也是相同的情况。

1、自定义监听事件(推荐)

// 广播:浏览器原生网页(top)位置进行消息广播

// 发送广播: top
let customEvent = new CustomEvent('my-message-type', { details: 'this is a message!'})
window.dispatchEvent(customEvent)

// 消息监听:content_script内容脚本进行监听
 window.addEventListener('my-message-type', (e) => {
   console.log(e)
   console.log(e?.details) // this is a message!
   // do something
 })

2、监听广播事件


// 发送广播消息:top
window.postMessage({'type': 'my-message-type', 'data': 'message!'}, '*')

// 监听消息:content_script
window.addEventListener('message', (e) => {
  console.log('e:', e)
  console.log('e.data:', e?.data)
  console.log('e.data.type:', e?.data?.type)
  console.log('e.data.data:', e?.data?.data)

  if (e?.data?.type === 'my-message-type') {
    // do something
  }
})

不推荐使用window.postMessage进行消息广播:
来源CSDN论坛评论:https://blog.csdn.net/dongzi_yu/article/details/128441466#comments_28957465
image.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小白说(๑• . •๑)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值