javascript - 按需获取 Facebook 访问 token ,但如何获取?

标签 javascript facebook firefox firefox-addon xul

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

这工作正常但有点愚蠢,因为没有人会在每个 firefox session 中使用扩展。所以我想做的是,获取访问 token 或更准确地调用 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() 仍在等待访问 token 时,onLoad() 方法不会等待并继续。因此,在发送请求时 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();
}

关于javascript - 按需获取 Facebook 访问 token ,但如何获取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10521928/

相关文章:

facebook - FQL 未返回我的所有好友

css - Firefox 中的谷歌字体呈现像素化

javascript - 仅在完成渲染图像时才计算 div 样式

javascript - 水平滚动,检测相对于 anchor 的滚动位置

javascript - Google Apps 脚本 - 从自定义菜单调用自定义函数 - 不嵌套

facebook - 页面 : how to retrieve link to attached file 的图形 API 直接消息

javascript - 如何使用 Ajax 和 HTML 结构来回显自动完成选项?

Facebook API : a strange query error 601

http - LiveHttpHeaders : which cache-control info is right

javascript - 如何找到某些事件上正在运行的 Javascript?