I am developing a Chrome extension that aims to extract the HTML code of the current webpage and display it in a popup window. However, I am facing the following error: "Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist." The error occurs when I click a button in the popup to trigger the extraction process.
Key Code Snippets:
Popup Script (popup.js):
document.getElementById("extractButton").addEventListener("click", function() {
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, { action: "extractHTML" });
});
});
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.action === "htmlExtracted") {
const extractedHTML = request.html;
document.getElementById("htmlDisplay").value = extractedHTML;
}
});
Content Script (content.js):
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.action === "extractHTML") {
const html = document.documentElement.outerHTML;
chrome.storage.local.set({ extractedHTML: html }, function() {
chrome.runtime.sendMessage({ action: "htmlExtracted", html: html });
});
}
});
Additional Notes:
The extension includes necessary permissions in manifest.json, such as "activeTab" and "storage". The content.js script is correctly injected into all URLs, as specified in the "content_scripts" section of manifest.json. I would appreciate any guidance or suggestions on resolving this issue. Thank you!
Steps to Reproduce:
Load the extension using "Load unpacked" in chrome://extensions/. Click on the extension icon to open the popup. Click on the "Extract HTML" button in the popup. Expected Behavior: Upon clicking the "Extract HTML" button, the extension should successfully send a message to the content script, extract the HTML of the current page, and display it in the popup window.
Actual Behavior: Instead, the extension encounters the "Could not establish connection. Receiving end does not exist" error, preventing successful communication between the popup and content scripts.