I am trying to create a chrome extension that sends the DOM body from the active tab to some backend server, which will return some response which I will do later. However, I cannot figure out how send information via event listeners from the content-script to the service-worker. Heres the code I have now: Service-Worker:
chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) {
if (request.action === "submit") {
console.log("submit stage 1")
const response_tabs = sendMessageToActiveTab('sendDOM')
console.log(response_tabs)
const response_runtime = chrome.runtime.sendMessage({message: 'sendDOM', action: 'sendDOM'})
console.log(response_runtime)
async function sendMessageToActiveTab(message) {
const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });
const response = await chrome.tabs.sendMessage(tab.id, {message: message, action: 'sendDOM'});
return response
}
Content-Script:
chrome.tabs.addListener(async function(request, sender, sendResponse) {
if (request.action === "sendDOM") {
const article = await document.querySelector("body");
console.log("article: ", article);
sendResponse(article);
return article;
}
});
chrome.runtime.onMessage.addListener(function(message, sender) {
if (message.action === "sendDOM") {
const article = await document.querySelector("body");
console.log("article: ", article);
sendResponse(article);
return article;
}
});
And manifest.json:
{
"manifest_version": 3,
"name": "Nuntia",
"version": "1.0",
"permissions": ["activeTab","tabs"],
"action": {
"default_popup": "popup.html"
},
"background": {
"service_worker": "service-worker.js"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content-script.js"]
}
],
"externally_connectable": {
"matches": ["*://*.google.com/*"]
},
"host_permissions": [
"http://*/*",
"https://*/*"
]
}
Any advice on how to go about doing this or fixing my approach would be greatly appreciated!
So far I have tried different ways to make the two js files communicate with each other such as chrome.tabs and chrome.runtime. Both are returning this same error