Your click event listener is never added to the DOM. You have:
document.addEventListener('DOMContentLoaded', function() {
When entering scripts, unless you explicitly inject into document_start , your script will be guaranteed to be entered at least after DOMContentLoaded already running. 1 Given that the event has already been fired and only fires once, your DOMContentLoaded listener DOMContentLoaded never called. As a result of how the injection works, you do not need to listen to the DOMContentLoaded event DOMContentLoaded all. Just move your initialization so that it runs in the main sequence of your code (after adding the button):
document.getElementById('button_id').addEventListener('click', function() { console.log("CLICK"); });
No need to search for the <button> that you create
However, in this case, you add this button yourself. No need to look for it in the DOM. You already have a link to it. Add a listener during button creation:
var button1 = document.createElement('button'); button1.id = 'button_id'; button1.textContent = 'Click me'; button1.addEventListener('click', function() { console.log("CLICK"); }); modal1.appendChild(button1);
Do not use generic identifiers or classes
For extensions, you should not use identifiers or classes that are common as button_id . This gives a good chance that you will have a clash of names with random pages into which you enter content. You must select the sequence of text that you use as the "namespace". You can then add this namespace to all identifiers and classes. For example, your identifier should look something like this: Study06-button_id . Exactly what you use is a personal choice. But this should be specific to the extension you are working on.
Each time you use the DOMContentLoaded or the window load listener, you should always check document.readyState so that you add a listener before the DOMContentLoaded event DOMContentLoaded (or load if that is what you are listening to). This should be a normal habit when you want to listen to these events. If you add a listener after the event has been fired, the listener will never be fired.
To add a DOMContentLoaded listener DOMContentLoaded you should use something like:
if(document.readyState === 'loading') { document.addEventListener('DOMContentLoaded',afterLoaded); } else { afterLoaded(); } function afterLoaded(){
- Note that when using
tabs.executeScript() you will have to seriously work when executing tabs.executeScript() in the time frame when the script is actually entered into document_start . The exact time it takes is different for different browsers. If you use manifest.json content_script , this time is handled by the browser.