webRequest.StreamFilter.ondata

An event handler that will be called repeatedly when response data is available. The handler is passed an event object which contains a data property, which contains a chunk of the response data as an ArrayBuffer.

Browser compatibility

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxOperaFirefox for Android
Basic supportChrome No support NoEdge No support NoFirefox Full support 57Opera No support NoFirefox Android Full support 57

Legend

Full support  
Full support
No support  
No support

Examples

This example adds an ondata listener which replaces "Example" in the response with "WebExtension Example".

Note that this example only works for occurrences of "Example" that are entirely contained within a data chunk, and not ones that straddle two chunks (which might happen ~0.1% of the time for large documents). Additionally it only deals with UTF-8-coded documents. A real implementation of this would have to be more complex.

function listener(details) {
  let filter = browser.webRequest.filterResponseData(details.requestId);
  let decoder = new TextDecoder("utf-8");
  let encoder = new TextEncoder();

  filter.ondata = event => {
    let str = decoder.decode(event.data, {stream: true});
    // Just change any instance of Example in the HTTP response
    // to WebExtension Example.
    str = str.replace(/Example/g, 'WebExtension Example');
    filter.write(encoder.encode(str));
    // Doing filter.disconnect(); here would make us process only
    // the first chunk, and let the rest through unchanged. Note
    // that this would break multi-byte characters that occur on
    // the chunk boundary!
  }

  filter.onstop = event => {
    filter.close();
  }

  //return {}; // not needed
}

browser.webRequest.onBeforeRequest.addListener(
  listener,
  {urls: ["https://example.com/*"], types: ["main_frame"]},
  ["blocking"]
);

Another example for handling  large documents:

function listener(details) {
  let filter = browser.webRequest.filterResponseData(details.requestId);
  let decoder = new TextDecoder("utf-8");
  let encoder = new TextEncoder();

  let str = "";
  filter.ondata = event => {
    str += decoder.decode(event.data, {stream: true});
  };

  filter.onstop = event => {
    // Just change any instance of Example in the HTTP response
    // to WebExtension Example.
    str = str.replace(/Example/g, 'WebExtension $&');
    filter.write(encoder.encode(str));
    filter.close();
  };
}

browser.webRequest.onBeforeRequest.addListener(
  listener,
  {urls: ["https://example.com/*"], types: ["main_frame"]},
  ["blocking"]
);

Document Tags and Contributors

Contributors to this page: kernp, wbamberg, Simon Lindholm
Last updated by: kernp,