Lishu
Lishu

Reputation: 1448

chrome extension popup cannot find element by ID

I know similar questions have been asked many times, but I didn't find a solution for mine yet. My question is really simple. All I want to do is to test actions on popup.html, for here, I have a click button on popup, when I click it, I want to show alert. But nothing happened. It's not finding the element. I don't understand what's going wrong here.

manefest.json

{
  "name": "test",
  "version": "1.0",
  "description": "test",
  "manifest_version":2,
  "browser_action": {
    "default_icon": "logo.png",
    "default_popup":"popup.html"
  },
  "permissions": [
    "tabs", 
    "http://*/*",
    "notifications"
  ]
}

popup.html

<html>
  <head>
    <title>Test</title>
    <script type="text/javascript" src="jquery.js"></script> 
    <script type="text/javascript" src="popup.js"></script>
  </head>
  <body>
    <button id='btn'>click</button>
  </body>
</html>

popup.js

$('#btn').click(function (){
   alert("test");
};

Upvotes: 1

Views: 2938

Answers (2)

Xan
Xan

Reputation: 77571

The problem is that your code executes as soon as <script> tag is read, i.e. before your element exists in DOM.

Wrap it in $(document).ready() and you're good to go:

$(document).ready(function() {
  /* your code */
});

For a non-jQuery solution, wrap it in DOMContentLoaded listener:

document.addEventListener("DOMContentLoaded", function() {
  /* your code */
});

Finally, you can simply move the <script> tag to the end of <body>, but it's a less robust solution.

Upvotes: 4

DeadlyChambers
DeadlyChambers

Reputation: 5284

I believe your popup.js syntax is wrong

  $('#btn').click(function (){
   alert("test"); 
};

should be

    $('#btn').click(function (){
   alert("test");
   });

looks like you are missing a paran;

Upvotes: 0

Related Questions