有能力的可以看官方文档: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通讯圆满结束,哈哈哈哈哈哈