Skip to content Skip to sidebar Skip to footer

Use ReadableStream With Response To Return HTML From Fetch Event Of Service Worker

I'm trying to return a stream for the HTML response in a service worker but the browser does not seem to be able to parse it (I'm using chrome for this test). So, this one works (i

Solution 1:

For some reason it doesn't work when you don't lock stream with ReadableStream.getReader

Also when you pass ReadableStream to Response ctor, the Response.text method doesn't process the stream and it returns toString() of an object instead.

const createStream = () => new ReadableStream({
  start(controller) {
    controller.enqueue("<h1 style=\"background: yellow;\">Yellow!</h1>")
    controller.close()
  }
})

const firstStream = createStream().getReader();
const secondStream = createStream().getReader();

new Response(firstStream, {
      headers: {
        "Content-Type": "text/html"
      }
    })
  .text()
  .then(text => {
    console.log(text);
  });
    

secondStream.read()
  .then(({
    value
  }) => {

    return new Response(value, {
      headers: {
        "Content-Type": "text/html"
      }
    });

  })
  .then(response => response.text())
  .then(text => {
    console.log(text);
  });

Post a Comment for "Use ReadableStream With Response To Return HTML From Fetch Event Of Service Worker"