I’m trying to handle EventStream POST requests using the webRequest API in a browser extension. I’m not able to correctly process the event-stream chunks sent by the server. My goal is to intercept the response chunks and store them in my script. Nothing prints and no error is shown.
The code is part of my background.js script, everything up until console.log('Event-Stream response intercepted:', details);
is working fine, so it is detecting the event-stream response:
browser.webRequest.onHeadersReceived.addListener((details) => {
if (details.statusCode === 200 && details.type === 'xmlhttprequest') {
for (let header of details.responseHeaders) {
if (
header.name.toLowerCase() === 'content-type'
&& header.value.toLowerCase().includes('event-stream')
) {
console.log('Event-Stream response intercepted:', details);
const filter = { urls: [details.url] };
const streamId = details.requestId;
// Filter response data
const filterData = browser.webRequest.filterResponseData(streamId);
const decoder = new TextDecoder('utf-8');
let dataBuffer = '';
filterData.ondata = (event) => {
const chunk = decoder.decode(event.data, { stream: true });
console.log('chunk', chunk);
dataBuffer += chunk;
// Process dataBuffer here or store it in eventStreamData for later use
eventStreamData.set(streamId, dataBuffer);
// Pass the chunk through without modifying it
filterData.write(event.data);
};
filterData.onstop = () => {
filterData.disconnect();
};
break;
}
}
}
},
{ urls: ['*://*.example.com/*'] },
['responseHeaders']
);
The console.log('chunk', chunk);
statement is not printing anything, so it seems like the stream is not being handled correctly. I’m not even sure that filterResponseData
is the correct approach here. What am I doing wrong, and how can I properly handle the event-stream chunks with the webRequest API in a browser extension?