如何在Firefox插件sdk扩展中使用main.js中的XMLHttpRequest。 (或类似的东西)

时间:2013-11-06 17:10:46

标签: javascript firefox firefox-addon firefox-addon-sdk

我有一个Firefox扩展,需要检查onUnload事件。基本上我想在用户禁用扩展时向我的服务器发送消息。

我尝试做的是向我的一个内容脚本发送一条消息,然后调用XMLHttpRequest。这适用于扩展触发的任何其他事件,但看起来内容脚本在消息甚至可以传递之前被卸载。

main.js

以下是main.js脚本中的代码:

exports.onUnload = function(reason) {
    //unloadWorker comes from a PageMod 'onAttach: function(worker){}'
    //That is called every time a page loads, so it will a recent worker.
    if(unloadWorker != null) { 
        unloadWorker.port.emit("sendOnUnloadEvent", settings, reason);
    }
};

内容脚本

以下是我附加到每个加载页面的内容脚本中的代码。

self.port.on("sendOnUnloadEvent", function(settings, reason) {
    console.log("sending on unload event to servers");
    settings.subid = reason;
    if(reason != "shutdown") {
        sendEvent(("on_unload"), settings);
    }
});

发送事件代码

最后,这里是发送事件代码,仅供参考我最初计划如何使用XMLHttpRequest:

sendEvent = function(eventName, settings) {

    if (!eventName) {
        eventName = "ping"; 
    }
    //Not the actual URL, but you get the idea.
    var url = 'http://example.com/sendData/?variables=value&var2=value2'

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {

    }

    xhr.open("GET", url, true);
    xhr.send();
}

无论如何都要使用main.js中的XMLHttpRequest吗?

或许是一种触发onUnload事件的方法,但是在扩展实际卸载之前触发它? (就像beforeOnUnload类型事件一样)

3 个答案:

答案 0 :(得分:7)

从main.js发出网络请求的首选方法是使用模块sdk/request中的Request对象。

但是,Request只能发出异步请求,这意味着当函数结束并且请求不会发生时,对象将超出范围。

相反,您可以使用sdk/net/xhr来使用XMLHttpRequest并在卸载时生成synchronous GET request,如下所示:

const {XMLHttpRequest} = require("sdk/net/xhr");
exports.onUnload = function(reason) {
    var url = 'http://mysite.com/sendData/?variables=value&var2=value2'
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, false);
    xhr.send(null);
});

但是请注意sdk/net/xhr被标记为不稳定,同步请求被阻止并且不受欢迎。

答案 1 :(得分:1)

我的解决方案与user2958125略有不同,所以我会在下面发布。

const {Cc, Ci} = require("chrome");
var xhr = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);
//var xhr = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Components.interfaces.nsIXMLHttpRequest);

xhr.onreadystatechange = function() {

}

xhr.open("GET", url, true);
xhr.send();

答案 2 :(得分:1)

function reqListener () {
  console.log(this.responseText);
}

const {XMLHttpRequest} = require("sdk/net/xhr");
var url = "http://ya.ru";
var xhr = new XMLHttpRequest();
xhr.onload = reqListener;
xhr.open('GET', url, false);
xhr.send(null);