I've been using a background script combined with jquery to get the source code of a page with a Chrome Extension but now, I'd like to capture the source code only when I click on the extension pop-up.
Here is what I have been trying to do:
popup.html
<!DOCTYPE html>
<html>
<head>
<title>Tab Source Code</title>
<script src="popup.js"></script>
</head>
<body>
<button id="getCodeButton">Get Source Code</button>
<pre id="sourceCode"></pre>
</body>
</html>
popup.js
document.addEventListener("DOMContentLoaded", function () {
var getCodeButton = document.getElementById("getCodeButton");
getCodeButton.addEventListener("click", function () {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, { action: "getSourceCode" }, function (response) {
console.log(response);
});
});
});
});
content.js
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.action === "getSourceCode") {
var sourceCode = document.documentElement.outerHTML;
sendResponse({ sourceCode: sourceCode });
}
});
When I run the screen, I get the following error message: Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.
My manifest seems ok:
{
"manifest_version": 2,
"name": "xxxx",
"description": "xxxx",
"version": "1.01",
"author": "xxxx",
"permissions": [
"tabs",
"http://*/",
"https://*/",
"<all_urls>",
"notifications",
"webRequest",
"webNavigation",
"management",
"webRequestBlocking",
"http://*/*",
"background",
"alarms",
"https://*/*"
],
"externally_connectable": { "matches": ["http:///", "https:///"] },
"background": {
"scripts": ["background.js"],
"persistent": true
},
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"js": ["content.js"]
}],
"browser_action": {
"default_icon": "logo.png",
"default_popup": "popup.html"
}
}
I have tried multiple solutions found on stackexchange to communicate with content.js but I haven't found one that works.
I tried this: Port error: Could not establish connection. Receiving end does not exist. In Chromiume but it doesn't solve my problem.
any idea ?
thanks