I am working on a chrome extension which should extract the video title from a YouTube page and show the title in the extension pop-up. This works when the popup is open and I refresh the page, but if the pop-up is closed I get this error while sending the message,
Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.
Is there a way that I can consistently send messages from content script to the pop-up even if the pop-up is closed?
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);
});
When the action popup is closed it doesn't run and can't receive messages.
Simply get the current title each time the popup is shown:
// 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;
})();
P.S. Note that the popup is a separate window so it has its own separate devtools: right-click inside the popup and select "inspect" in the menu.