1

I'm trying to build a firefox extension that will implement a login form on a remote website. Basically the extension will open up a popup by clicking on the extension icon near the adress bar. The popup behaviour i achieved using this module

https://github.com/Rob--W/browser-action-jplib

First time when i tried to build the javascript login script i implemented the ajax call to the remote website in a data script not in main.js. This solution was wrong because from what i've read the ajax calls are not supported in the data scrips, and i need to make it using request module in the main.js. Fallowing this i used the request module in the main.js and come up to the next code :

data.js(Script inside data folder used in the popup)

 extension.sendMessage(
         {
              action:"login",
              data:{user:user,password:password}
         },function(r){
    //Handle server response. If ok show post login screen if not show invalid credentials.
  });

main. js

var popup = badge.BrowserAction({
    default_icon: data.url("icon.png"),    
    default_popup: data.url("popup.html")      
}) 

popup.onMessage.addListener(function(message, sender, sendResponse) {

      if(message.action == 'login'){
             sendResponse(login(message.data));
      } 
});
function login(data  ){ 

    var ret;
    login = Request({
          url: url,
          content:data, 
          onComplete: function (response) {   
                ret = response.json;
          }
    });
    login.get();

        return ret;
}

Because request is asynchronous i get null response sent back to data.js. i have looked over the request module documentation and didnt find a solution to this.

Does anyone have or know a solution to fix this issue ?

Thank you !

4

1 回答 1

0

sendResponse这实际上非常简单——在你得到回应之前不要打电话。您可以将sendResponse函数作为回调传递给您的login函数:

popup.onMessage.addListener(function(message, sender, sendResponse) {
      if(message.action == 'login'){
             login(message.data, sendResponse);
      }
      return true;
});
function login(data, callback){
  ...
  onComplete: function(response) {
    callback(response.json);
  }
  ...
}
于 2013-10-27T08:41:49.867 回答