Intercepting load events

I am interested in catching loads before they hit the network. The docs say

Properties relating to the tab’s content (for example: title, favicon, and url) will not be correct at [the ‘open’ event]. If you need to access these properties, listen for the ready event

That implies there is no way to get a target URL before Firefox starts resolving it. I want to inspect the target URL before sending any packets and decide whether to cancel, forward, or tweak it at that point. Is there an undocumented part of the SDK that allows this? I tried tab.on('loadstart') but got nothing.

I’ve found this loadContent thing in demo form only which sounds like it should do what I want, but it’s very complex and I can’t figure out how it fits into the high level API, if it does at all.

They don’t want everyone messing with that stuff so the SDK doesn’t offer an API for it. There are low level APIs that allow you to do it. You can set up a content policy handler, which allows you to block any content from being loaded. Note that this is called on each http response, and you only get the choice to allow or block.

For more detailed work, you use an http request observer. All http requests will get passed to you, where you can pass it though unchanged, alter headers, redirect, or completely cancel the request. This is generally done in an XPCOM component which requires chrome. An http observer can be set up at any time but won’t catch requests made earlier, so ideally it is initialised from a chrome manifest. Usually you would observe http-on-modify-request which is called effectively when XHR.send() is called. You do have the option to observe http-on-opening-request which is called when XHR.open() is called but this is usually unnecessary. It is also a bad idea since your handler is called synchronously before the open() call returns which slows everything down.

Right. That sounds complicated, but as I get more into this I am sure I will figure out all the parts you mentioned. Thank you.

I can offer my jetpack-requestmod module( it’s on npm), which uses the observer topics under the hood.

1 Like

I see you recommend the new WebRequest in your README. Great! This is just what I need.

There are four things you can do with a request:

  • cancel it
  • redirect it
  • modify request headers
  • modify response headers.
1 Like

Be careful. WebRequest isn’t quite the same as the WebExtensions WebRequest API so not compatible with Google Chrome. It is also still quite buggy. It will be good once they get it working properly though. I tried it a few months back and it wouldn’t do all the things I need, although I notice a couple of things have been fixed already.