1.先在contentScript里面创建一个端口,并且发送一个消息
contentScript.js
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
background.js
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发送消息的实例
popup.js
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, { greeting: "hello" }, function (
response
) {
console.log(response.farewell);
});
});
复制代码
contentScript
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!" });
}
});
复制代码
最后记得在manifest.json中添加background配置:
"background": {
"scripts": ["lib/axios.js", "background.js"]
},
复制代码
参考文档:http://chrome.cenchy.com/messaging.html
作者: Bill 本文地址: http://biaoblog.cn/info?id=1622688540000
版权声明: 本文为原创文章,版权归 biaoblog 个人博客 所有,欢迎分享本文,转载请保留出处,谢谢!