Is it possible to know the target DOMWindow for an

2019-01-24 18:19发布

问题:

I'm developing a firefox extension which requires me to intercept page loads by filtering out some HTTPRequests. I did that using the instructions given here. Please note that my question draws from the content of this link.

I used the method given under the section of HTTPObservers. And it worked, I am indeed able to extract the respective urls of the Requests being sent out.

However, another thing which I really require is to get the target DOM Window where the contents pertaining to the HTTPRequest were about to be loaded. Is it possible using HTTPObservers?

In the link above, another way has been described using WebProgressListeners.

I tried that out as well. The onLocationChange() method only returns location changes in the url bar. Is it somehow possible to get the HTTPRequest urls using any of these progress listeners? Because if so, then if I understand correctly, aWebProgress.DOMWindow would give me the window I require.

Note: I am using gwt for the extension and the JSNI for the above mentioned part.

回答1:

You can usually do that by using nsILoadContext interface (sadly barely documented) attached to the request or its load group. Here is how you would do that:

function getWindowForRequest(request)
{
  if (request instanceof Components.interfaces.nsIRequest)
  {
    try
    {
      if (request.notificationCallbacks)
      {
        return request.notificationCallbacks
                      .getInterface(Components.interfaces.nsILoadContext)
                      .associatedWindow;
      }
    } catch(e) {}

    try
    {
      if (request.loadGroup && request.loadGroup.notificationCallbacks)
      {
        return request.loadGroup.notificationCallbacks
                      .getInterface(Components.interfaces.nsILoadContext)
                      .associatedWindow;
      }
    } catch(e) {}
  }

  return null;
}

Note that this function is expected to return null occasionally - not every HTTP request is associated with a window.