I'm working on creating a Chrome extension, and I'm having trouble with adding a button with an onclick event listener to a page using Chrome Content Scripts. I did look at a lot of similar posts, including this one which suggests injecting scripts. I injected a script to my content script, and everything I have in the injected script (creating the button on the content page) works, except creating the event listener - nothing happens when I click on the button.
My content script injects a script to manipulate the DOM of the page:
function injectScript() {
const s = document.createElement('script');
s.src = chrome.runtime.getURL('readlater.js'); //my inject script
(document.head || document.documentElement).appendChild(s);
s.remove();
}
And the injected script creates a button & an event listener:
const btn = document.createElement('button');
btn.setAttribute('id', 'mybtn');
btn.innerHTML = 'click me!';
document.body.append(btn);
console.log(document.getElementById('mybtn')); //the elt is found
document.getElementById('mybtn').addEventListener('click', function () {
alert('clicked!');
});
I added the inject script to manifest.json, like so: "web_accessible_resources": ["readlater.js"]
.
The button (or any html I tried) is being created, however, clicking on the button is never registered by the listener. What is the right way of setting up event listeners? Thank you!