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 !
It's actually very simple - don't call sendResponse
until you have the response. You can pass the sendResponse
function as a callback to your login
function:
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);
}
...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.