Modify Response Body

This script shows how to modify a response body.

addEventListener("fetch", event => {
  event.respondWith(fetchAndModify(event.request));
});

async function fetchAndModify(request) {
  const response = await fetch(request);

  // Check response is html content
  if (
    !response.headers.get("content-type") ||
    !response.headers.get("content-type").includes("text/html")
  ) {
    return response;
  }

  // Read response body.
  const text = await response.text();

  // Modify it.
  const modified = text.replace("<body", '<body style="direction:rtl"');

  // Return modified response.
  return new Response(modified, {
    status: response.status,
    statusText: response.statusText,
    headers: response.headers
  });
}