前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >chrome 插件通信DEOM

chrome 插件通信DEOM

作者头像
copy_left
发布2020-09-01 14:54:10
7250
发布2020-09-01 14:54:10
举报
文章被收录于专栏:方球
基础概念
  • 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))
})
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 基础概念
  • 插件内的通信方法
  • DEMO
    • 1. 页面端
      • 2. content_script
        • 3. backgound
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档