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

编程知识 更新时间:2023-04-05 06:01:15

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>

更多推荐

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

本文发布于:2023-04-05 06:01:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/f045fbb8d251fe838d653078a649250f.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:通信   content   chrome   script   js

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 45154文章数
  • 14阅读数
  • 0评论数