在Google chrome扩展开发中使用内容脚本传递消息时遇到问题,我的代码结构如下所示:
popup.html:
var oList;
function getHTML()
{
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {action:"getHTML"}, function handler(response) {
oList = response.dom;
});
});
alert("oList = "+oList );
}我的内容脚本看起来像这样:
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if(request.action == "getHTML"){
sendResponse({dom: document.getElementsByTagName("HTML").length});
}
});当我通过在popup.html中的"oList = response.dom;“处放置一个断点来调试代码时,我从内容脚本中获得了正确的值设置。但是在执行扩展时,来自popup.html的"alert("oList = "+oList );“代码似乎是在它到达服务器之前先执行的。因此,它的值没有被设置。有没有人能告诉我我是不是错了?
发布于 2010-08-13 08:22:25
大多数Chrome API方法都是异步的。这意味着当你调用它们时,脚本不会等待它们的响应,而只是继续执行。如果你想在响应上执行一些东西,你应该把它放在回调函数中:
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {action:"getHTML"}, function handler(response) {
oList = response.dom;
alert("oList = "+oList );
});
});https://stackoverflow.com/questions/3472881
复制相似问题