1.先在contentScript里面创建一个端口,并且发送一个消息
saveDetail() {
var port = chrome.extension.connect({ name: "menu" });
port.postMessage({ detail: { name: "hello!?~" } });
//这里主要是为了接受回传的值
port.onMessage.addListener((msg) => {
if (msg.res) {
console.log(msg.res);
}
});
},
},
2.然后在background.js里面接受,并且进行api访问,拿到结果再回传给contentScript
chrome.extension.onConnect.addListener(function (port) {
console.log(port);
if (port.name === "menu") {
port.onMessage.addListener(function (msg) {
if (msg.detail) {
axios.get("http://biaoblog.run:3000/blogData/mood").then((res) => {
port.postMessage({ res });
});
}
});
}
});
3.添加popup向contentScript发送消息的实例
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, { greeting: "hello" }, function (
response
) {
console.log(response.farewell);
});
});
chrome.runtime.onMessage.addListener(function (
request,
sender,
sendResponse
) {
console.log(
sender.tab
? "from a content script:" + sender.tab.url
: "from the extension"
);
if (request.greeting == "hello") {
sendResponse({ farewell: "I'm contentscript,goodbye!" });
}
});
"background": {
"scripts": ["lib/axios.js", "background.js"]
},