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

Gar*_*ett 4 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);
    }
};
Run Code Online (Sandbox Code Playgroud)

内容脚本

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

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);
    }
});
Run Code Online (Sandbox Code Playgroud)

发送事件代码

最后,这里是发送事件代码,仅供参考我最初计划如何使用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();
}
Run Code Online (Sandbox Code Playgroud)

反正有没有从main.js使用XMLHttpRequest?

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

use*_*125 7

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

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

相反,你可以使用sdk/net/xhr,以便能够在卸载时使用XMLHttpRequest和发出同步GET请求,如下所示:

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);
});
Run Code Online (Sandbox Code Playgroud)

但请记住,sdk/net/xhr标记为不稳定,同步请求是阻塞和不赞成的.

  • 我在谈论答案本身,而不是你对它的评论;) (2认同)