chrome扩展中,content-script与background.js之间的通信

background.js发消息给content-script

  • background.js发送
// bg---->content
chrome.tabs.query({
  active: true,
  currentWindow: true
}, (tabs) => {
  let message = {
    //这里的内容就是发送至content-script的内容
    info: window.localStorage.getItem('isShow')
  }
  chrome.tabs.sendMessage(tabs[0].id, message, res => {
    console.log('bg=>content')
    console.log(res)
  })
})
  • content-script接收
// get popup2content info
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    console.log(request.info)
    // 这里是返回给bg的内容
    sendResponse('get the message')
})

content-script发消息给background.js

  • content-script发送

Chrome提供的大部分API是不支持在content_scripts中运行
sendMessage onMessage 是可以使用

chrome.runtime.sendMessage({
  info: isShow
}, res => {
  // 答复
  // alert(res)
})
  • background.js接收
chrome.runtime.onMessage.addListener((req, sender, sendResponse) => {
  const res = req.info
  console.log(res)
})

补充

  • backgroundpopup发消息
// background.js中
function toPopup () {
  alert('to popup')
}
// popup.js中
const bg = chrome.extension.getBackgroundPage()
document.getElementById('btn').onclick = function () {
  bg.toPopup()
}
popup.html中


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button id="btn">click</button>

    <script src="./popup.js"></script>
  </body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值