[英]Firefox addon sdk synchronous request
I'm trying to build a firefox extension that will implement a login form on a remote website. 我正在尝试构建一个将在远程网站上实现登录表单的firefox扩展。 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 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. 第一次尝试构建javascript登录脚本时,我使用不是main.js中的数据脚本实现了对远程网站的ajax调用。 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.
这个解决方案是错误的,因为从我阅读的内容来看,数据脚本不支持ajax调用,而我需要使用main.js中的request模块来实现。 Fallowing this i used the request module in the main.js and come up to the next code :
为此,我在main.js中使用了request模块,并转到下一个代码:
data.js(Script inside data folder used in the popup) data.js(弹出窗口中使用的数据文件夹中的脚本)
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
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. 因为请求是异步的,所以我将空响应发送回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. 这实际上非常简单-在获得响应之前不要调用
sendResponse
。 You can pass the sendResponse
function as a callback to your login
function: 您可以将
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);
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.