Problem:
I’am sure this topic has already been discussed somewhere on this website but as a newbie I can’t really figure this out on my own..
I’am trying to code a very “simple” chrome extension so that when a user clicks on a certain button, it triggers an alert.
As far as I understood, the click needs to be listened then the background has to communicate with my content in order to display the alert.
Here is my code :
Manifest
{
"name": "Test alert",
"version": "1.0",
"manifest_version": 2,
"description": "This is a test",
"browser_action": {
"default_icon": "icon.png"
},
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"content_scripts" : [{
"matches": ["<all_urls>"],
"js" : ["content.js"]
}]
}
Background
document.getElementById("edit-payment").addEventListener("click", function(tabs){
chrome.tabs.sendMessage(tabs[0].id, {action: "saySomething"}); });
Content
chrome.runtime.onMessage.addListener(function (msg) {
if (msg.action === 'saySomething') {
alert('hello');
}
});
I’am having trouble when it comes to message passing. Can anyone enlighten me pls ?
Thank you for your time !
I’ve been trying to use chrome.tabs but something is wrong.
Solution:
The background script doesn’t have access to the document and
document.getElementById("edit-payment")
won’t work. It is the content script that has access to it!
The service worker (background script):
The extension service worker handles and listens for browser events. There are many types of events, such as navigating to a new page, removing a bookmark, or closing a tab. It can use all the Chrome APIs, but it cannot interact directly with the content of web pages; that’s the job of content scripts.
See: https://developer.chrome.com/docs/extensions/mv3/getstarted/extensions-101/#extension-files