页面注入的JS脚本和Content Script(内容脚本)的通信

背景:
        通过创建元素的方式向页面注入js脚本不能直接通过chrome API完成和Content Script(扩展内容脚本)之间的的消息通信。
        下面就是怎么把消息从注入脚本 发送到 内容脚本

  1. 向页面注入一个节点
    以向百度注入一段页面元素为例:
    在这里插入图片描述
let buttonEle = document.createElement('button');
buttonEle.onclick = 'window.postMessage({message:"要向content script发送的消息"}, '*'); alert("按钮注入")';
buttonEle.style = 'width: 110px;height: 44px;background-color: #f65c14;border-radius: 0 10px 10px 0;font-size: 17px;color: #fff;border: none;';
buttonEle.innerText = '注入此按钮'

================== 如下


<button onclick="window.postMessage({'message':'message'}, '*'); alert('按钮注入')" style="
    width: 110px;
    height: 44px;
    background-color: #f65c14;
    border-radius: 0 10px 10px 0;
    font-size: 17px;
    color: #fff;
    border: none;
    ">注入此按钮</button>


================== 重点!!!注入的脚本发送消息

window.postMessage({type: "inject_message_type", message:"要向content script发送的消息", '*'})
  1. Content Script 内容脚本监听注入脚本发送的消息
// 接收:window.postMessage 发送的消息。内容脚本 监听 注入脚本 发送的消息  (content script)
window.addEventListener('message', (e) => {
  console.log('ZMessageEvent:', e)
  if (e && e.data && e.data.type === 'inject_message_type') {
    // TODO LIST
    // 由内容脚本调用 chrome API 完成和background的交互
  }
})
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小白说(๑• . •๑)

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

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

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

打赏作者

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

抵扣说明:

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

余额充值