从内容脚本向弹出窗口发送消息,即使弹出窗口关闭



我正在制作一个chrome扩展,应该从YouTube页面提取视频标题,并在扩展弹出框中显示标题。当弹出窗口打开并刷新页面时,这可以工作,但如果弹出窗口关闭,我在发送消息时得到此错误,

Uncaught (in promise) Error: Could not establish connection。接收端不存在

是否有一种方法,我可以始终如一地从内容脚本发送消息到弹出窗口,即使弹出窗口关闭?

content.js

window.onload = () => {
const videoTitle = document.querySelector(
"#title h1 yt-formatted-string"
)?.textContent;
if (videoTitle) {
chrome.runtime.sendMessage(chrome.runtime.id, {
type: "VIDEO_NAME",
value: videoTitle,
});
}
};

popup.js

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
console.log("Request: ", request, "Sender: ", sender);
});

当动作弹出窗口关闭时,它不会运行,也无法接收消息。

只需在每次弹出窗口显示时获取当前标题:

//popup.js

(async () => {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
const [{ result }] = await chrome.scripting.executeScript(({
target: { tabId: tab.id },
func: () => document.querySelector('#title h1 yt-formatted-string')?.textContent,
}));
document.body.textContent = result;
})();

注:请注意,弹出窗口是一个单独的窗口,因此它有自己单独的devtools:右键单击弹出窗口内并选择">

最新更新