理想是火,点燃熄灭的灯。
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"] },
参考文档:http://chrome.cenchy.com/messaging.html
作者: Bill 本文地址: http://biaoblog.cn/info?id=1622688540000
版权声明: 本文为原创文章,版权归 biaoblog 个人博客 所有,欢迎分享本文,转载请保留出处,谢谢!