Sending mail from Chrome extension using auth 2.0 but stuck at somewhere I don't know

孤者浪人 提交于 2020-01-05 09:29:51

问题


I want to send email from Chrome extension where user has to enter the email address of the reciepent in the extenion popup window, and the link of the current opened tab will be sent to the entered email address, but I am stuck in the authentication part, it asks for the password of my email as shown in the.

After I enter, it reloads the same page instead of sending the mail. Please help me out where I am getting wrong. The code is for popup.js page.

document.addEventListener('DOMContentLoaded', function () {
    document.querySelector('button').addEventListener('click', getCurrentTabAndUrl);

});

function getCurrentTabAndUrl() {

  chrome.tabs.getSelected(null, function(tab) {

        var tabId = tab.id;
        var tabTitle=tab.title;
        var tabUrl = tab.url;
        if (tabUrl=="chrome://newtab/") {
          document.getElementById("data").innerHTML="Looks like you opened a new tab, please open a web page and click again to Share.";
        }else {
        document.getElementById("data").innerHTML="subject="+tabTitle+'<br/>'+tabUrl;

        var to=document.getElementById("to").value;


        sendMessage('me',to,tabTitle,tabUrl);

        }
    });
}


function sendMessage(userId,to,subject,email) {

  authUser();

  var base64EncodedEmail = btoa(email);

  var request = gapi.client.gmail.users.messages.send({

    'userId': userId,

    'message': {
      'raw': base64EncodedEmail,

      "headers":[
        {"To":to},
        {"Subject":subject}
          ]
    }
  });

  request.execute();

}

function authUser(){

    chrome.identity.getAuthToken(
    {'interactive': true},
    function(token){
     // load Google's javascript client libraries
     var url="https://www.googleapis.com/gmail/v1/users/me/messages/send?access_token="+token;
        var request = new XMLHttpRequest();

    request.onreadystatechange = function(){
        if(request.readyState !== 4||request.status !== 200) {
            return;
        }

   var response=JSON.parse(request.responseText);
   console.log(response);

    };
    request.open('POST', url,true);

    request.send();
    request.setRequestHeader('Authorization','Bearer ' + token);
    });

}

回答1:


After invoking authUser(), which calls an asynchronous API chrome.identity.getAuthToken, you're immediately sending the email so it fails as the token hasn't yet been acquired.

Move that part into a callback which will be executed after getAuthToken completes:

function sendMessage(userId, to, subject, email) {
    authUser(function() {
        var base64EncodedEmail = btoa(email);
        var request = gapi.client.gmail.users.messages.send({
            'userId': userId,
            'message': {
                'raw': base64EncodedEmail,
                'headers': [
                    {'To': to}, 
                    {'Subject': subject}
                ]
            }
        });
        request.execute();
    });
}

function authUser(callback) {
    chrome.identity.getAuthToken({'interactive': true}, function(token) {
        // load Google's javascript client libraries
        var url = "https://www.googleapis.com/gmail/v1/users/me/messages/send?access_token=" + token;
        var request = new XMLHttpRequest();
        request.onreadystatechange = function() {
            if (request.readyState !== 4 || request.status !== 200) {
                return;
            }
            var response = JSON.parse(request.responseText);
            console.log(response);
            callback();
        }
        ;
        request.open('POST', url, true);
        request.send();
        request.setRequestHeader('Authorization', 'Bearer ' + token);
    });
}


来源:https://stackoverflow.com/questions/31741960/sending-mail-from-chrome-extension-using-auth-2-0-but-stuck-at-somewhere-i-dont

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!