Event not triggering on a content scripts Chrome extension

Viewed 257

I'm building a content scripts Chrome extension. I've dynamically added a button to a webpage, however the event listener on this button won't trigger.

Here is manifest.json:

{
  "manifest_version": 2,
  "name": "my extension",
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "activeTab"
  ],
  "content_scripts": [
      {
        "matches": ["http://127.0.0.1:8000/*"],
        "js": ["jquery.js", "script.js"],
        "run_at": "document_end"
      }
  ]
}

This is script.js:

document.body.style.backgroundColor = "yellow";
var button = $('<input id="btn" type="button"/>');
$("body").append(button);  

$("#btn").on("click", function(){
    document.body.style.backgroundColor = "red"; 
});

The button is added to the page and background changes to yellow, but it doesn't change to red when clicking button.

2 Answers
Related