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.
If the suspected issue is with the button ID - note that you don't need the ID at all.
document.body.style.backgroundColor = "yellow";
var button = $('<input id="btn" type="button"/>');
$("body").append(button);
button.on("click", function(){ // Notice you don't need to search for it again!
document.body.style.backgroundColor = "red";
});
However, in this case you'll need to keep the button
variable to find it again.
This unique id may help you ;)
document.body.style.backgroundColor = "yellow";
uniqueId = 'btn' + Date.now();
var button = $('<input id="' + uniqueId + '" type="button"/>');
$("body").append(button);
$("#" + uniqueId).on("click", function(){
document.body.style.backgroundColor = "red";
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.