理想是火,点燃熄灭的灯。
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.cn: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"] },
background.js / poppup.js
// 遍历所有已打开的tab 全部发送 chrome.tabs.query({}, function (tabs) { // 遍历标签页数组 for (var i = 0; i < tabs.length; i++) { // 向每个标签页的 content script 发送消息 chrome.tabs.sendMessage(tabs[i].id, { greeting: "formBackground", data: shadeValue, }); } });
contentscript
//监听从poppup 输入框的变化 并重新调整dom的阴影值 chrome.runtime.onMessage.addListener(function ( request, sender, sendResponse ) { if (request.greeting == "formBackground") { console.log(request); console.log("formBackground!!!"); } });
作者: Bill 本文地址: http://biaoblog.cn/info?id=1622688540000
版权声明: 本文为原创文章,版权归 biaoblog 个人博客 所有,欢迎分享本文,转载请保留出处,谢谢!