Search code examples
javascriptgoogle-chrome-extensiondom-events

Chrome extension JavaScript eventlistener not working in content script


I am trying to add an event listener to my content script for a Chrome extension I am working on.

My content script:

   console.log("test 1");
document.addEventListener('DOMContentLoaded', function () {
    console.log("test 2");
});

I know the content script is working because the first message is printed. However, the event listener is never fired for me.

What am I missing? I feel as if it is something silly.

My manifest.json

{
    "manifest_version": 2,

    "name": "test",
    "description": "testtesttesttest",
    "version": "1.0",
    "permissions": [
        "tabs", "http://*/*", "https://*/*"
    ],
    "browser_action": {
        "default_popup": "popup.html",
        "default_title": "Settings"
    },
    "permissions": [
    "tabs", "http://*/*", "https://*/*"
    ],
    "content_scripts": [{
        "matches": ["http://*/*","https://*/*"],
        "js": ["colorLink.js"],
        "run_at": "document_end", 
        "all_frames": true
    }]
}

Solution

  • The content script is injected at "run_at": "document_end" which occurs after DOMContentLoaded. In this case you don't need an event listener.