So, I’m thinking of making an extension that changes the response depending on some conditions. Like, if request hit a URL at /graphql
, using POST, and the request body has a certain key-value pair; then modify the response.
const newResponse = {...};
const callback = (details) => {
const url = new URL(details.url);
if (details.method !== 'POST') return { cancel: false };
if (details.requestBody.raw.length < 1) return { cancel: false };
const bodyRaw = details.requestBody.raw[0];
const bodyBytes = bodyRaw.bytes;
const bodyUint8Array = new Uint8Array(bodyBytes);
const bodyString = new TextDecoder().decode(bodyUint8Array);
const body = JSON.parse(bodyString);
if (body.key !== 'value') return { cancel: false };
return {
redirectUrl: "data:application/json;charset=utf-8," +
encodeURIComponent(JSON.stringify(newResponse))
};
};
const filter = {
types: [ 'xmlhttprequest' ],
urls: [ 'http://*/graphql' ]
};
const opt_extraInfoSpec = [
'blocking',
'requestBody'
];
chrome.webRequest.onBeforeRequest.addListener(
callback, filter, opt_extraInfoSpec
);
I know the code is only good for Manifest V2 or older, and webRequestBlocking
is deprecated in Manifest V3.
But how do I grab requestBody
using declarativeNetRequest
or some other trick to get this code migrating smoothly in Manifest V3?
New contributor
Dwi Siswanto is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.