1

使用 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});   
     }
  });

oList = response.dom;当我通过在我的 popup.html中的“”处放置一个断点来调试我的代码时,我从内容脚本中获得了正确的值集。但是在执行扩展alert("oList = "+oList );程序时,popup.html 中的“”代码似乎在它进入服务器之前首先执行。因此,它的值没有被设置。有人可以告诉我我是否在某个地方错了?

4

1 回答 1

5

大多数 Chrome API 方法都是异步的。这意味着当您调用它们时,脚本不会等待它们的响应,而是继续执行。如果你想在响应中执行一些东西,你应该把它放在回调函数中:

chrome.tabs.getSelected(null, function(tab) {
 chrome.tabs.sendRequest(tab.id, {action:"getHTML"}, function handler(response) {
  oList = response.dom;
  alert("oList = "+oList );
 });
});
于 2010-08-13T00:22:25.253 回答