基础概念
- manifest.json 插件配置
- content_script 注入脚本,可读取页面中的dom,以及window对象方法
- backgound 插件脚本,
页面与插件之间的同行管道:
页面 -> content_script : dom
content_script -> background : chrome.runtime
插件内的通信方法
- chrome.runtime.sendMessage 发送数据
- chrome.runtime.onMessage.addListener 接收数据
DEMO
1. 页面端
代码语言:javascript复制// 页面内配置通信dom
<div id='plugin-pip'/>
代码语言:javascript复制// 页面通信插件
const PIP_DOM_ID = 'plugin-pip'
const SEND_KEY = 'SEND_MSG_FROM_APP'
const LISTENER_KEY = 'LISTENER_PLUGIN_MSG'
const DATA_SAVE_KEY = 'DATA-MSG'
export class PluginPip{
static instance = null
constructor(){
if(PluginPip.instance){
return PluginPip.instance
}
this.pip = document.querySelector(`#${this.conf.PIP_DOM_ID}`)
this.listener = new Set()
this.init()
PluginPip.instance = this
}
init(){
this.pip.addEventListener(this.conf.LISTENER_KEY, (e) =>{
console.log(e)
let data = {}
try {
data = JSON.parse(this.pip.getAttribute(this.conf.DATA_SAVE_KEY))
} catch (error) {
console.error("插件接收数据格式化失败: ", error)
}
this.listener.forEach(callback => callback(data))
})
}
send(type, data={}){
const msg = {type, data}
let msgStr = ''
console.table('send: ', msg)
try {
msgStr = JSON.stringify(data)
} catch (error) {
console.error("插件发送数据格式化失败: ", error)
return error
}
sessionStorage.setItem(this.conf.DATA_SAVE_KEY, msgStr)
const evt = document.createEvent("HTMLEvents");
evt.initEvent(this.conf.SEND_KEY, false, false);
this.pip.dispatchEvent(evt)
}
// 获取配置
get conf(){
return PluginPip.conf()
}
// 获取配置静态方法
static conf(){
return {
PIP_DOM_ID,
SEND_KEY,
LISTENER_KEY,
DATA_SAVE_KEY
}
}
}
// 初始化插件
const pip = new PluginPip()
// 添加接收
pip.listener.add((data) =>{
console.log('from plugin: ', data)
})
// 发送数据
pip.send("msg", {id: 'xx', name:'xx'})
2. content_script
代码语言:javascript复制// 获取通信管道
const pip = document.querySelector('#plugin-pip')
// 配置接收
pip.addEventListener("SEND_MSG_FROM_APP", (s) =>{
const msg = window.sessionStorage.getItem('DATA-MSG')
console.log("from app: ", msg)
// 转发到backgfound
chrome.runtime.sendMessage(msg, () =>{})
})
3. backgound
代码语言:javascript复制// 接收 content_script 消息
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse){
console.log(JSON.parse(msg))
})