1

I'm writing a firefox addon and I want to do something before every http request is issued. Pseudocode:

observerService.addObserver(httpRequestObserver, "http-on-modify-request", false);
var httpRequestObserver=
{
    observe: function()
    {
            var httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);

            asyncFunction1(){
                // asynchronous function No.1
            }.then(asyncFunction2(){
                // asynchronous function No.2, this function will be called after asyncFunction1 finished
                // do something to httpChannel (edit the request header etc.)
            });
        //point 1
    }
}

The problem is that asyncFunction2() may finishes after observe() finished. And according to Firefox, the request will be issued after observe() finished. Thus when asyncFunction2() is editing httpChannel, the variable 'httpChannel' is already out of date(because observe() ends).

To keep the request not issued before asyncFunction2() finished, I need to do sth to let the main thread wait for asyncFunction2() at point 1. I have tried to put 'setTimeout(function waitfor(){},xxxx)' at point 1, but waitfor() starts after observe() ends. I also tried to put asyncFunction1&2 in a chrome workder(similar to web worker) and let the worker thread sends a message when asyncFunction2 finished. However, javascript seems unable to be interrupted when executing the main thread. What i found is that javascript only put the 'receive a message ! event' into the task queue. Thus when javascript is dealing with the message, the observe() has already returned.

kennn9
  • 51
  • 3
  • *"Thus when asyncFunction2() is editing httpChannel, the variable 'httpChannel' is already out of date(because observe() ends)"* - But the variable `httpChannel` will be accessible within `asyncFunction2()` even after the `observe()` function ends. (Though the object it refers to may not be "alive", whatever that means in your context.) – nnnnnn Jan 21 '15 at 08:00
  • It's true that httpChannel is accessible in asyncFunction2, but editing httpChannel is meaningless then because the object ( the request ) is already issued. – kennn9 Jan 21 '15 at 08:09
  • see [this question](http://stackoverflow.com/questions/5205672/modify-url-before-loading-page-in-firefox/) for how to reissue it as a new request, that should allow you to stall it a little bit – the8472 Jan 21 '15 at 16:52

0 Answers0