The Chrome extension popup is not working, click events are not handled
Your code is not working because it violates the default Content Security Policy. I've created a screencast of one minute to show what's wrong:
First, I've shown how to debug the problem. Right-click on your popup button, and click on "Inspect popup". After doing that, you will see the following error message:
Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:".
This explains that your code is not working, because it violates the default CSP: Inline JavaScript will not be executed. To solve the problem, you have to remove all inline JavaScript from your HTML file, and put it in a separate JS file.
The result is shown below:
hello.html
(popup page)
<!DOCTYPE html><html><head></head><body><p id="demo">=a</p><button type="button" id="do-count">Count</button><script src="popup.js"></script></body></html>
popup.js
var a=0;function count() { a++; document.getElementById('demo').textContent = a;}document.getElementById('do-count').onclick = count;
Note that I've replaced innerHTML
with textContent
. Learn to use textContent
instead of innerHTML
when you intend to change the text. In this simple example it does not matter, but in more complex applications, it might become a security issue in the form of XSS.
Change your onclick
:
onclick="count"
Or change your count function to something like this:
function count(){ var demo = document.getElementById("demo"); return function() { demo.innerHTML = ++a; }}
Here is a nice demo I put together:
Code (this assumes that you add id="the_button"
to your button):
window.onload = function () { var button = document.getElementById("the_button"); button.onclick = count(); function count() { var a = 0; var demo = document.getElementById("demo"); return function () { demo.innerHTML = ++a; } }}