我想通过单击innerHTML中的按钮来执行chrome扩展程序(在popup.js中)中的函数。
我在 popup.html 中的代码是:
<html>
<head>
<script src="popup.js"></script>
</head>
<body>
<div id="panier_container"> </div>
</body>
</html>
我在 popup.js 中的代码:
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
if (msg.text === 'results') {
var panier_container = document.getElementById("panier_container");
var texte = "<button onclick=\"toto()\"> TOTO </button>";
panier_container.innerHTML = texte;
});
});
function toto() {
alert("toto");
}
当我执行代码时,我看到按钮“TOTO”,但是当我单击该按钮时,没有任何反应。出自chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
按钮执行该功能。但里面没有。
最佳答案
我建议使用 JavaScript DOM 函数而不是 html onclick 属性来附加该函数。 Chrome 扩展程序不允许在 HTML 中使用内联 javascript,请参阅 this SO question以及 Chrome 开发者文档 here 。如果您为按钮提供一个方便的句柄(例如 id)并使用 .addClickListener()
会怎么样?相反?
var panier_container = document.getElementById("panier_container");
var texte = "<button id='totoButton'> TOTO </button>";
panier_container.innerHTML = texte;
document.getElementById("totoButton").addEventListener("click", toto);
function toto() {
alert("toto");
}
还值得注意的是,您可能想要移动您的 <script>
标记到 <body>
的末尾或者给它一个async
属性,因为根据脚本标记的位置,#panier_container
可能尚未加载,请参阅the first answer here了解浏览器如何解释脚本标签。
关于javascript - Chrome 扩展中 popup.html 和 popup.js 之间的 JavaScript 函数(考虑到来自后台的消息),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43527502/