浏览器扩展开发之脚本通信

498 阅读1分钟

主要讲两种比较常用的连接方式:第一种是使用chrome.runtime.sendMessage(),另外一种是使用长连接之后port.postMessage()方式

  1. 通信完成即断开连接: chrome.runtime.sendMessage

content_script 主动向 background 发送消息,需要先在background中添加监听消息事件,在content_script中发送消息,反之亦然

chrome.runtime.sendMessage({ type: 'search', value: '123' }, response => {
  console.log('我接收到background返回的值是', response)
})

background 中的写法,直接调用参数中的sendResponse方法即可

注意如果background里面监听的事件中有异步操作的话,一定要先返回一个 true,不然content_script收不到消息

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  console.log('我接收到content_script发来的消息是', request)
  sendResponse({
    status: 200,
    data: [
      { id: 1, name: 'jack' },
      { id: 2, name: 'tom' }
    ]
  })
  return true
})
  1. 使用长连接,在background中监听连接,在content_script创建连接

background中一开始就监听连接事件,代码如下

chrome.runtime.onConnect.addListener(port => {
  // 这里可以拿到 port.name 来判断是什么连接,比如
  if (port.name === 'search') {
    // 这里处理搜索的相关逻辑,然后使用port.postMessage([])返回消息
    port.postMessage({
      status: 200,
      data: [
        { id: 1, name: 'tom' },
        { id: 2, name: 'jack' }
      ]
    })
  }
})

content_script中创建连接,啥时候创建,取决于你的业务逻辑,比如我一开始就创建

const port = chrome.runtime.connect({ name: 'search' }) // 1. 创建连接
port.onMessage.addListener(result => {
  console.log('background返回给我的内容是', result)
})

// 然后可以弄一个输入框,监听里面的值变化之后,进行查询操作
port.postMessage('123213')

注意

  • 有可能这个连接会断开,所以要进行相关逻辑处理,比如重新连接等等
  • background 和 content_script 均要进行 onMessage 的事件监听