I am making a Firefox add-on and I need it to have the ability to modify the bodies of certain outgoing HTTP requests. The instructions for modifying headers are readily available on Mozilla's own documentation, but that's not what I'm looking for. There is no mention of modifying the HTTP body on this page.
To modify HTTP headers, one would need to use the webRequest
API's onBeforeSendHeaders
(docs) event. However with onBeforeSendHeaders
, you are unable to pass the HTTP request's body to the listener (the function that is called when this event is triggered), so this would not help.
onBeforeRequest
(docs), on the other hand, does allow the body to be passed to the listener. However, there is no mention of modifying the body. It only mentions canceling and redirecting the request. Therefore I assume that this cannot be used to modify request bodies either.
This event is triggered when a request is about to be made, and before headers are available. This is a good place to listen if you want to cancel or redirect the request.
Nonetheless, I still made an attempt at modifying outgoing HTTP requests' bodies. I tested this on Discord's web app.
const text = "http mod test"
function replaceBody(details) {
let originalBody = details.requestBody.raw[0].bytes;
let encoder = new TextEncoder;
let decoder = new TextDecoder;
let jsonBody = JSON.parse(decoder.decode(originalBody));
jsonBody.content = text;
let newBody = encoder.encode(JSON.stringify(jsonBody));
return { requestBody: newBody }
}
browser.webRequest.onBeforeRequest.addListener(
replaceBody,
{urls: ["*://discord.com/api/v9/channels/*"]},
["blocking", "requestBody"]
);
So it should've replaced any message I sent with "http mod test", but it didn't. No errors or warnings either. When I checked the "Network" section of the Developer Tools (Ctrl + Shift + E or Cmd + Opt + E) and checked the body of the POST request, it sure enough contained my original message (i.e. not "http mod test") I tried returning the unencoded JSON string instead, but that was also to no avail.
The short answer is "no."
There is no API to write to request bodies, only to read them. Previous to the move to the webextensions API (FF 57), it was possible. For example, there was an add-on called TamperData that was exceedingly popular. Since then, there have been other add-ons that have called themselves TamperData, but do not have the same capability.
The slightly longer answer is "maybe." It depends on what you want to do.
If you want to alter form submission in a POST request, you can intercept the submit event, alter the form, then allow the action to continue. (See Is there a way to modify the POST data in an extension now? for some discussion.)
If you want to alter HttpRequest bodies in general, you'd have to create a separate proxy to intercept them and alter them. You can't get an extension to do that.