0

I followed the steps to develop a Chrome extension from dev docs https://developer.chrome.com/docs/extensions/mv3/getstarted/development-basics/

But my popup.js is not working, even loading the "hello world" extension example from documentation the scripts remains doing nothing.

My extension structure:


extension
├── images
│   ├── icon-128.png
│   ├── icon-16.png
│   ├── icon-32.png
│   ├── icon-48.png
│   └── icon-64.png
├── manifest.json
├── popup.css
├── popup.html
└── popup.js

Manifest.json

{
  "manifest_version": 3,
  "name": "My extension",
  "description": "Extension example",
  "version": "1.0",
  "action": {
    "default_popup": "popup.html",
    "default_icon": "images/icon-48.png"
  },
  "icons": {
    "16": "images/icon-16.png",
    "32": "images/icon-32.png",
    "48": "images/icon-48.png",
    "128": "images/icon-128.png"
  }
}

Popup.html

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="popup.css">
</head>
<body>

    <div class="cta-wrapper">
        <button id="cta-btn" class="btn">CLICK ME</button>
    </div>

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

</body>
</html>


Popup.js

document.getElementById('cta-btn').addEventListener('click', function(e) {
    console.log('Click')
})

I tried with a simple console.log in popup.js but do nothing. Any idea of what is happening?

  • Is there an error in the console? – epascarello Nov 14 '22 at 17:16
  • I tried this on my side and it worked. You are probably looking in the wrong console! The console for the popup needs to be opened directly by opening the pop up window, right clicking the pop up, and press "Inspect". Let me know if you still have problems. – Jridyard Nov 14 '22 at 17:18
  • @epascarello No errors are displayed – Guillermo Reyes Nov 14 '22 at 17:21
  • If you add a console.log line in the popup.js (not in the click listener) does it get triggered? – epascarello Nov 14 '22 at 17:22
  • @GuillermoReyes Please read me comment. I recreated your exact code and it worked. I promise you the issue is that you're looking in the wrong console. Try exchanging ```console.log``` for ```alert``` and you will see it work. – Jridyard Nov 14 '22 at 17:23
  • 1
    @JoeRidyard You are right! I was on the wrong console. Thank you very much, I was already pulling my hair out ⭐ – Guillermo Reyes Nov 14 '22 at 17:28
  • @GuillermoReyes No problem, I remember what it was like building my first chrome extensions - those kind of issues came up all the time hah! – Jridyard Nov 14 '22 at 17:29

1 Answers1

-2

You should wrap click event registration code on window's load event.

Like this,

window.addEventListener('load', () => {
  document.getElementById('cta-btn').addEventListener('click', clickOnButton);
});
function clickOnButton(e) {
  console.log('Click');
}
Daxay Makwana
  • 65
  • 1
  • 5