Javascript chrome扩展:如何从后台页面获取异步结果

Javascript chrome扩展:如何从后台页面获取异步结果,javascript,asynchronous,google-chrome-extension,Javascript,Asynchronous,Google Chrome Extension,因为我无法从内容脚本中使用identity对象,所以我尝试通过后台JS进行身份验证 内容脚本: chrome.runtime.sendMessage({Action: "GetToken"}, function(response) { var token = response.Result; // never gets here } 背景脚本: chrome.runtime.onMessage.addListener( function(request, sender, sendR

因为我无法从内容脚本中使用identity对象,所以我尝试通过后台JS进行身份验证

内容脚本:

chrome.runtime.sendMessage({Action: "GetToken"}, function(response)
{
   var token = response.Result; // never gets here
}
背景脚本:

chrome.runtime.onMessage.addListener(
   function(request, sender, sendResponse)
   {
      if (request.Action === "GetToken")
      {
         chrome.identity.getAuthToken({'interactive': true}, function(token)
         {
            console.log("token:"+token);
            sendResponse({Result: token});
         });
   }
});
我可以在后台脚本的控制台中看到令牌是接收到的令牌:xxxxxx

但它从未收到内容脚本。我认为这是一个线程问题;没有向控制台写入错误。如何避免这种混乱局面?

调用getAuthToken后,您只需返回true即可