I simply defined the code that popup.js
, background.js
, and content.js
communicate, but nothing is printed to the console and they don't seem to be communicating with each other. I think the message exchange is like this-
popup.js
(button click) -> background.js
-> content.js
-> background.js
-> popup.js
.
manifest.json
{
"manifest_version": 3,
"name": "Chrome Extension",
"version": "0.1.0",
"description": "project",
"icons": {
"32": "icons/icon_32.png"
},
"background": {
"service_worker": "background.js",
"icon": "icon-34.png"
},
"action": {
"default_title": "Chrome Extension",
"default_popup": "popup.html"
},
"host_permissions": [
"https://*/*"
],
"permissions": [
"storage",
"activeTab",
"tabs",
"scripting"
]
}
popup.js
function start(){
let link = document.getElementById('request-btn');
if(link){
link.addEventListener('click', function() {
console.log('click check'); // This code prints to the console.
chrome.runtime.sendMessage({
type: "popup_send"
})
});
}
}
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.type === "html") {
console.log("HTML received in popup.js: ", request.data);
console.log('popup check');
}
});
window.onload = start;
background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.type === "content_send") {
chrome.runtime.sendMessage({
type: "html",
data: "background_send"
})
} else if(request.type === 'popup_send'){
chrome.runtime.sendMessage({
type: "content_request"
})
}
});
content.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
if(request.type === "content_request"){
chrome.runtime.sendMessage({
type: "content_send"
})
}
})
Only "click check" is outputted to the console when I click the button.
What's the problem?