我正在构建一个 content scripts
Chrome 扩展。我在网页上动态添加了一个按钮,但是此按钮上的事件监听器不会触发。
这是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"
}
]
}
这是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";
});
按钮被添加到页面中,背景变成黄色,但点击按钮时没有变成红色。
最佳答案
如果怀疑问题与按钮 ID 有关 - 请注意,您根本不需要该 ID。
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";
});
但是,在这种情况下,您需要保留 button
变量才能再次找到它。
关于javascript - 事件不会在内容脚本 Chrome 扩展程序上触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36172895/