首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Chrome扩展: chrome.runtime.onMessage.addListener内部的功能

问Chrome扩展: chrome.runtime.onMessage.addListener内部的功能
EN

Stack Overflow用户
提问于 2017-04-24 15:45:23
回答 1查看 1.5K关注 0票数 0

几天来,我遇到了一个关于不执行函数的.js脚本中的按钮的问题。

这里我的代码在popup.html里面

代码语言:javascript
复制
<html>
<head>
<script src="popup.js"></script>
</head>

<body>
<div id="panier_container"> </div>
</body>

</html>

这里我的代码在popup.js里面

代码语言:javascript
复制
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {

//Message en provenance du background
if (msg.text === 'panier') {
var panier_container = document.getElementById("panier_container");
panier_container.innerHTML ="<button id=\"totoButton\"> Affiche TOTO    </button>";
 }   

});

//Fonction toto
function toto() {
    alert("toto");
}

document.addEventListener('DOMContentLoaded', function() {
document.getElementById("totoButton").addEventListener("click", toto);
});

当我执行代码时,我会看到弹出窗口中的按钮,但是当我单击该按钮时,什么也不会发生。关于信息,msg来自于我的background.js。

但是,如果我在popup.js中编写这段代码,就可以了:

代码语言:javascript
复制
var panier_container = document.getElementById("panier_container");
panier_container.innerHTML ="<button id=\"totoButton\"> Affiche TOTO </button>";

//Fonction toto
function toto() {
    alert("toto");
}

document.addEventListener('DOMContentLoaded', function() {
document.getElementById("totoButton").addEventListener("click", toto);
});

使用这段代码,我看到了按钮,当我单击它时,我看到了toto (函数被执行)。

您知道为什么循环chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {中的按钮不执行toto函数吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-24 16:06:49

请为popup.js尝试以下操作:

代码语言:javascript
复制
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {

//Fonction toto
function toto() {
    alert("toto");
}

//Message en provenance du background
if (msg.text === 'panier') {
var panier_container = document.getElementById("panier_container");
panier_container.innerHTML ="<button id=\"totoButton\"> Affiche TOTO    </button>";  //create the button
document.getElementById("totoButton").addEventListener("click", toto);  //attach listener to button just created.
 }   

});

在实际元素存在之前,代码document.getElementById("totoButton").addEventListener("click", toto);被称为,因为元素是在收到消息后创建的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43592472

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档