Page Rewriting

Last update:2024-09-03 17:00:36

This example demonstrates how to achieve dynamic content adaptation using Edge Cloud Apps Function. The code snippet below illustrates how to dynamically rewrite page content based on the visitor’s browser type. If the user is accessing the page using Chrome, the content will be rewritten; otherwise, the original content will remain unchanged.

Code Example

async function handleRequest(request) {
    // Fetch the original request and retrieve the response
    let response = await fetch(request);
    // Set a custom response header
    response.headers.set("X-Version", "petshop-v1");

    // Check if the request is from a Chrome browser and the response content type is HTML
    if (isFromChrome(request) && isHtml(response)) {
        console.log("Rewriting page content...");

        // Retrieve the response body text and perform replacements
        let body = await response.text();
        body = body.replace('Make Your Pets Happy');
        body = body.replace(
            'Dolore tempor clita lorem rebum kasd eirmod dolore diam eos kasd.',
        );

        // Return the modified response
        return new Response(body, response);
    } else {
        console.log("Passing through original page content...");
        return response;
    }
}

// Determine if the request originated from a Chrome browser
function isFromChrome(request) {
    let userAgent = request.headers.get("User-Agent");
    return userAgent && userAgent.toLowerCase().includes("chrome");
}

// Determine if the response content type is HTML
function isHtml(response) {
    let contentType = response.headers.get("Content-Type");
    return contentType && contentType.toLowerCase().includes("text/html");
}

// Add a Fetch event listener to handle incoming requests
addEventListener("fetch", event => {
    event.respondWith(handleRequest(event.request));
});

Notes

This example demonstrates how to implement dynamic content adaptation by detecting the user’s browser type and modifying the HTML content accordingly. Content rewriting has numerous applications, and below are a few mature online scenarios:

  • Profanity Filtering: Automatically detect and replace profanity in the page content.
  • External Link Rewriting: Dynamically modify the addresses of external links on the page.
  • Website IPv6 Support: Deliver content tailored to the visitor’s IP type.
Is the content of this document helpful to you?
Yes
I have suggestion
Submitted successfully! Thank you very much for your feedback, we will continue to strive to do better!