【发布时间】:2015-04-19 01:48:48
【问题描述】:
我正在创建一个 chrome 扩展。我在将消息从 background.js 发送到 popup.js 时遇到问题。我成功地将一些静态数据从 background.js 发送到 popup.js。但是,当我尝试从 background.js 动态发送数据(即 content-script.js 发送到 background.js 的数据)到 popup.js 时,当我在 popup.html 上打印它时,它给出了未定义的结果。
这是我的 popup.js:
var value;
window.onload = function(){
chrome.runtime.sendMessage({getVal: "Hi"}, function(response){
value = response.responseSeltext;
alert(value);
});
document.getElementById('save').onclick = test;
}
这是我的 background.js:
var seltext;
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.ezynotes != ""){
seltext = request.ezynotes;
alert("In extension "+seltext);
//document.getElementById("notes").innerHTML += request.ezynotes;
}
if (request.getVal != ""){
sendResponse({responseSeltext:seltext});
//seltext = request.ezynotes;
alert("In extension "+seltext);
//document.getElementById("notes").innerHTML += request.ezynotes;
}
});
【问题讨论】:
-
您能否不要使用
alert()进行调试?它会从您的弹出窗口中窃取焦点并可能使其关闭。此外,众所周知,由于阻塞执行会导致问题。 -
我尝试删除所有警报,但它仍然在 popup.html 上给出 undefined。
-
你如何测试它是未定义的?另外,如果您还没有,请尝试通过右键单击扩展按钮并选择“检查弹出窗口”来进行调试。
标签: google-chrome-extension background popup content-script