NebulaServices / Dynamic

[BETA] The new generation of interception proxies.
https://npmjs.com/@nebula-services/dynamic
GNU Lesser General Public License v3.0
55 stars 129 forks source link

How do i modify response content? #68

Closed akwin1234 closed 5 months ago

akwin1234 commented 5 months ago

sw.js:

` self.addEventListener('fetch', event => { event.respondWith( (async function() { if (await dynamic.route(event)) { return await dynamic.fetch(event); }

            return await fetch(event.request);
        })()
    );
}

);`

i want to modify the return value. But my approach is not working, My code:

`self.addEventListener('fetch', event => { event.respondWith( (async function() { // Check if the request URL contains a specific keyword, e.g., 'nike' const urlString = event.request.url.toString();

        // Function to modify response text if it contains a specific string
        async function modifyResponseText(response) {
            let text = await response.text(); // Read the response text

            if(!text.includes("<!DOCTYPE html>"))
                return response;
            if (text.includes('</body>')) {
                console.log('Original Response Status:', response.status);

               text = text.replace('</body>', "change or add a css here to hide ads or anything else</body>");
            }

            return new Response(text, {
                headers: response.headers,
                status: response.status,
                statusText: response.statusText
            });
        }

        // Check for custom routing logic
        if (await dynamic.route(event)) {
            const response = await dynamic.fetch(event);
            // Modify the dynamic response if needed
            return modifyResponseText(response);
        } else {
            // Fetch the default response and modify if needed
            const defaultResponse = await fetch(event.request);
            return modifyResponseText(defaultResponse);
        }
    })()
);

});`

Error i face here, attached.

wNrNHhD

what is a proper approach to modify? problem lies in: return new Response(text, { headers: response.headers, status: response.status, statusText: response.statusText });

akwin1234 commented 5 months ago

EDIT: i was modify a constant my bad