1

How can I attach an event to a button on the popup of a chrome extension? I read this https://developer.chrome.com/extensions/contentSecurityPolicy#JSExecution and still can't make it work; the script just executes the "awesome" functions once and then my button does nothing.

PD: I'm a beginner at both Javascript and Chrome extensions, so I'm not sure where exactly am I doing something wrong. I'll add both tags, if that's ok.

Edit: I add the code for my extension, although is almost the same as in the example in the developer.chrome link.

popup.html

<!doctype html> <html> <head> <title>Getting Started Extension's Popup</title> <script src="creatediv.js"></script> </head> <body> <button id="aaaa">something</button> </body> </html> 

creatediv.js

document.addEventListener('DOMContentLoaded', function () { document.getElementById('aaaa').addEventListener('click', loadDiv()); }); function loadDiv(){ var myDiv = document.createElement("div"); document.documentElement.appendChild(myDiv); myDiv.id = "mydiv"; myDiv.innerHTML = "asdf"; alert(123); return false; }; 

When I click on the extension icon the loadDiv function gets executed: i get a window alert with 123 on it and then a div with "asdf" is appeneded to popup.html. The button "something" does nothing.

3
  • So you want a button click to call a function in the background script? Commented Apr 30, 2014 at 12:50
  • You need to show us your code if you want us to figure out what's wrong. Include your html and javascript for your popup please. Commented Apr 30, 2014 at 12:53
  • Edited with my actual code. On a second thought I don't think there's any problem with it being a chrome extension; it also doesn't work when I open popup.html as a regular website, though it worked when I used onclick(). Commented Apr 30, 2014 at 13:58

1 Answer 1

2

It should be:

document.getElementById('aaaa').addEventListener('click', loadDiv); 

This executes loadDiv when the event triggers while your code executes loadDiv when you add the listener.

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, that was it! Thank you very much, this was killing me.
Can't believe I didn't catch that. +1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.