In content.js, I am trying to add an event listener to a button on the page but I keep getting this error:
Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
I have tried to put it in document.addEventListener('DOMContentLoaded',afterDOMLoaded); but DOMContentLoaded never fires in the content.js script. How can I add an event listener to a button on the page?
You should show how your content.js is executed.
Maybe, the page has already DOMContentLoaded when your script is inejcted.
The injection timing can be specified in manifest file.
If your manifest file is the following, your content.js is injected immediately after the window.onload event fires, that is after DOMContentLoaded.
Refer https://developer.chrome.com/docs/extensions/mv3/content_scripts/.
"content_scripts": [
{
"matches": ["https://*/*"],
"run_at": "document_idle",
"js": ["content.js"]
}
If your manifest is like the above, you do not need event listener, just write the code in content.js script instead.