Search code examples
javascripthtmlgoogle-chrome-extension

Chrome Extension .addEventListener never fired


I'm trying to build a chrome extension for the first time. I have a simple button, that launches a youtube webpage. But I can't seem to figure out why the button's event listener is never fired.

The index.html:

<!DOCTYPE html>
<html>
<head>
    <style>
        button {
            height: 100px;
            width: 100px;
        }
    </style>
</head>
<body>
    <button id="youtube-button">YouTube</button>

    <script>
        document.getElementById("youtube-button").addEventListener("click", function() {
            console.log('clicked youtoob button!')
            window.open("https://www.youtube.com/");
        });
    </script>
</body>
</html>

The manifest:

{
    "manifest_version": 2,
    "name": "YouTube Button",
    "description": "A button that opens YouTube",
    "version": "1.0",
    "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "index.html"
    },
    "permissions": [
        "activeTab"
    ]
}

The console.log('clicked youtoob button!') is never fired inside the developer console when I click the button.

What am I doing incorrectly?


Solution

  • The chrome console indicates that you are facing a problem similar to this Script causes “Refused to execute inline script: Either the 'unsafe-inline' keyword, a hash… or a nonce is required to enable inline execution”. To see your error precisely, you can right click and do 'inspect' on your button.

    As indicated, the cleanest way to do this is do create a new file in your directory, called openYoutube.js for example that contains this:

    document.getElementById("youtube-button").addEventListener("click", function() {
      console.log('clicked youtoob button!')
      window.open("https://www.youtube.com/");
    });
    

    and then call it in your html file like this

    <script src="openYoutube.js"></script>