昨天介紹了 extension Message Passing 的方法
今天想就 三方溝通範例:content ⇔ background ⇔ popup 詳細說明
// content_script.js
chrome.runtime.sendMessage({ action: "GET_PROJECT_KEY" }, (response) => {
console.log("從 background 收到:", response.projectKey);
});
// background.js
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === "GET_PROJECT_KEY") {
const projectKey = extractProjectKeyFromUrl(sender.tab.url);
sendResponse({ projectKey });
}
});
// popup.html
document.getElementById("getKeyBtn").addEventListener("click", () => {
chrome.runtime.sendMessage({ action: "FETCH_KEY" }, (response) => {
document.getElementById("output").innerText = response.projectKey;
});
});
// background.js
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === "FETCH_KEY") {
// 透過 tabs 與當前作用中的頁籤互動
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.tabs.sendMessage(tabs[0].id, { action: "GET_PROJECT_KEY" }, (resp) => {
sendResponse({ projectKey: resp?.projectKey || "未知專案" });
});
});
return true; // 必須 return true 才能啟用 async sendResponse
}
});