The Chrome extension popup is not working, click events are not handled

Sainath picture Sainath · Jul 11, 2013 · Viewed 43.4k times · Source

I have created a JavaScript variable and when I click on the button it should increment by 1, but its not happening.

Here's manifest.json.

{
  "name":"Facebook",
  "version":"1.0",
  "description":"My Facebook Profile",
  "manifest_version":2,
  "browser_action":{
    "default_icon":"google-plus-red-128.png",
    "default_popup":"hello.html"
  }
}

Here is the code for the html page

<!DOCTYPE html>
<html>
<head>
<script>
var a=0;
function count()
{
  a++;
  document.getElementById("demo").innerHTML=a;
  return a;
}
</script>
</head>
<body>
<p id="demo">=a</p>
<button type="button" onclick="count()">Count</button>
</body>
</html>

I want the extension to show me the value of a and increment it by one each time I click on the extension or the button

picture of the extension

Answer

Rob W picture Rob W · Jul 12, 2013

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:

screencast

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.