简体   繁体   English

getAuthToken回调中的sendResponse不起作用

[英]sendResponse in a getAuthToken callback doesn't work

I am having trouble with using sendResponse from my background script to my popup script. 我从后台脚本到弹出脚本使用sendResponse遇到麻烦。 I have discovered that the problem concerns that I am trying to sendResponse from within the getAuthToken callback. 我发现该问题与我试图从getAuthToken回调中发送sendResponse有关。 How do I get around this? 我该如何解决?

chrome.extension.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.task == "auth") {
      chrome.identity.getAuthToken({
        'interactive': true
      }, function(token) {
        if (chrome.runtime.lastError) {
          alert(chrome.runtime.lastError.message);
          return;
        }
      })

      var x = new XMLHttpRequest();
      x.open('GET', 'https://www.googleapis.com/oauth2/v2/userinfo?alt=json&access_token=' + token);

      x.onload = function() {
        if (x.readyState = 200) {
          var data = this.responseText;
          jsonResponse = JSON.parse(data);
          sendResponse({
            response: jsonResponse
          }); //return the email to the popup
          return true;
        };
      }
      x.send();
    }; //end of auth

You have to return true from the callback you pass to addListener to be able to use sendResponse from asynchronously running code. 您必须从传递给addListener的回调中返回true ,才能使用异步运行的代码中的sendResponse。 Here it is in the documentation 文档中

In the above example, sendResponse was called synchronously. 在上面的示例中,sendResponse被同步调用。 If you want to asynchronously use sendResponse, add return true; 如果您要异步使用sendResponse,请添加return true;否则,请执行以下步骤。 to the onMessage event handler. 到onMessage事件处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM