chrome extensions插件中popue.js和background.js进行通讯manifest V3版

本文介绍了如何在Chrome扩展中实现background.js与content.js之间的通信,通过chrome.runtime.sendMessageAPI进行交互,并提供了示例代码展示监听与响应消息的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有能力的可以看官方文档:https://developer.chrome.com/docs/extensions/reference/runtime/

如果想和content.js进行通讯,请看:https://xiaoshen.blog.csdn.net/article/details/128830779

其实原理都差不多,只是用的通讯方法不一样,和background.js进行通讯用的方法是:

chrome.runtime.sendMessage(
  extensionId?: string,
  message: any,
  options?: object,
  callback?: function,
)

 首先要在background.js里面开启监听消息的方法:

  // 消息传递
  const user = {
    username: 'demo-user'
  };

  chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    // 2. A page requested user data, respond with a copy of `user`
    console.log('这是background脚本onMessage', message);
    if (message === 'get-user-data') {
      sendResponse(user);
    } else {
      console.log('background脚本onMessage: else', message);
      sendContent(message)
    }
    sendResponse(user);
  });

  // 给content.js发送消息
  async function sendContent(tabID) {
    const response = await chrome.tabs.sendMessage(tabID, { greeting: "hello" });
    // do something with response here, not outside the function
    console.log("sendContentResponse---", response);
  }

然后在popue.js里面开启按钮的监听事件,然后发一个消息给background.js:

不过这次用的方法是:

const response = await chrome.runtime.sendMessage(tab.id); 

在popue.html里面添加一个按钮:

点击插件,然后可以看到:

 

点击一下之后,右键打开插件的检查:可以看到日志输出

然后打开百度页面的检查:可以看到backgroun.js给content.js通讯也成功了

至此说明,和background.js通讯圆满结束,哈哈哈哈哈哈

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

1024小神

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值