JimJJ
JimJJ

Reputation: 61

Why is script in popup.js not working?

Can someone help me, I'm building my first chrome extension and it's a popup with a button that's supposed to do something on click (just using alert now), but somehow whatever in my js file doesn't seem to be working. Styles also seem not to load.

manifest:

{
  "name": "Toolbar",
  "manifest_version": 2,
  "version": "1.0.2",
  "description": "Toolbar",

  "background": {
    "scripts": ["background.js"]
  },

  "browser_action": {
    "default_icon": "icon.png",
    "default_title": "None",
    "default_popup": "popup.html"
  },

  "permissions": [
    "tabs", "http://*/", "https://*/"
  ]
}

popup.html:

<html>

<head>
    <link rel="stylesheet" type="text/css" href="styles.css">
    <script src="popup.js"></script>
</head>

<body>
<div>
    <button type="button" id="closeButton"> x<button/>
</div>
</body>

</html>

popup.js:

function closePopup ()
{
    //window.close();
    alert("hello");
}

document.addEventListener('DOMContentLoaded', function() {
  document.getElementById('closeButton').on("click", function (){
      closePopup();
    }
  });
});

Upvotes: 1

Views: 3805

Answers (2)

Aditi Viswanathan
Aditi Viswanathan

Reputation: 1

You've got to put the <script src="popup.js"></script> in the <body> instead of <head> tag. That worked for me.

Upvotes: 0

Lukas Baum
Lukas Baum

Reputation: 11

<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<!--<script src="popup.js"></script> delete this-->
</head>
<body>
<div>
<button type="button" id="closeButton"> x<button/>
</div>
<!--add this--><script src="popup.js"></script>
</body>
</html>

place the script after the object, where the eventlistener is placed on. I had the same problem and that fixed it

Upvotes: 1

Related Questions