按需捕获Facebook Access令牌,但如何

Catch Facebook Access token on demand, but how?

本文关键字:令牌 Access Facebook      更新时间:2023-09-26

我构建了一个Firefox扩展,我正在使用图形API。目前,我在启动浏览器时捕获每个用户的访问令牌,例如:https://stackoverflow.com/questions/10301146/facebook-login-within-a-firefox-add-on

这工作正常,但有点愚蠢,因为没有人会在每个 Firefox 会话中使用该扩展。所以我要做的是,捕获访问令牌或更准确地调用 Wladimir Palant 按需推荐的方法。我的代码看起来像这样,而getAccessToken()是提到的方法。

onLoad: function (){
   var NoteHandler = window.arguments[0];
   var sjcl = NoteHandler.sjcl;
   NoteHandler.getAccessToken();
   decryptionDialog.noteHandler = NoteHandler;
   decryptionDialog.sjcl = sjcl;
   var currID = decryptionDialog.getID();
   if(currID==""){
      window.close();
      return false;
     }else{             
       http_request = new XMLHttpRequest();   
       http_request.open('Get', 'https://graph.facebook.com/'+currID+'/notes?access_token='+NoteHandler.token, false);
       http_request.overrideMimeType("text/json");
       http_request.send(null);
       decryptionDialog.value = decryptionDialog.ResponseToArray(http_request.responseText);
....

但问题是,当getAccessToken()仍在等待访问令牌时,onLoad()-Method不会等待并继续前进。因此,在发送请求时,NoteHandler.token 为空。有没有人有一个想法,因为我对javascript相对较新。

你应该重写这段异步的代码 - 它不应该假设getAccessToken()会立即得到结果,而应该有一个回调参数,一个在操作完成时调用的函数(可以是闭包函数)。大致如下:

onLoad: function (){
   var NoteHandler = window.arguments[0];
   var sjcl = NoteHandler.sjcl;
   NoteHandler.getAccessToken(function()
   {
       decryptionDialog.noteHandler = NoteHandler;
       decryptionDialog.sjcl = sjcl;
       ...
       http_request.open('Get', 'https://graph.facebook.com/'+currID+'/notes?access_token='+NoteHandler.token, false);
       ...
   });
}
...
getAccessToken: function(callback) {
    ...
    // All done - call the callback
    callback();
}