代码之家  ›  专栏  ›  技术社区  ›  sharath

Chrome扩展开发:消息传递问题

  •  1
  • sharath  · 技术社区  · 16 年前

    在googlechrome扩展开发中使用内容脚本传递消息时出现问题 我的代码结构如下所示:

    弹出窗口.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 ); “代码 未设置。。有人能告诉我哪里错了吗?

    1 回复  |  直到 16 年前
        1
  •  5
  •   serg    16 年前

    大多数chromeapi方法都是异步的。这意味着当您调用它们时,脚本不会等待它们的响应,而是继续执行。如果要在响应时执行某些操作,应将其放入回调函数中:

    chrome.tabs.getSelected(null, function(tab) {
     chrome.tabs.sendRequest(tab.id, {action:"getHTML"}, function handler(response) {
      oList = response.dom;
      alert("oList = "+oList );
     });
    });