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

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发送的消息", '*'})
- 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万+

被折叠的 条评论
为什么被折叠?



