我构建了一个 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/