From 341463fabade2094cc970f373a6d9e7cd5662b3c Mon Sep 17 00:00:00 2001 From: Percs <83934299+Percslol@users.noreply.github.com> Date: Sat, 20 Jul 2024 19:11:34 -0500 Subject: [PATCH] add script injection to page --- src/uv.sw.js | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/src/uv.sw.js b/src/uv.sw.js index c7c3d7cd..b9b5a32b 100644 --- a/src/uv.sw.js +++ b/src/uv.sw.js @@ -237,8 +237,43 @@ class UVServiceWorker extends Ultraviolet.EventEmitter { case 'iframe': case 'document': if (responseCtx.getHeader("content-type").startsWith("text/html")) { + let modifiedResponse = await response.text(); + if (Array.isArray(this.config.inject)) { + const headPosition = modifiedResponse.indexOf(''); + const upperHead = modifiedResponse.indexOf(''); + const bodyPosition = modifiedResponse.indexOf(''); + const upperBody = modifiedResponse.indexOf(''); + const url = new URL(fetchedURL) + const injectArray = this.config.inject; + for (const inject of injectArray) { + const regex = new RegExp(inject.host) + if (regex.test(url.host)) { + if (inject.injectTo === "head") { + if (headPosition !== -1 || upperHead !== -1) { + modifiedResponse = + modifiedResponse.slice( + 0, + headPosition + ) + + `${inject.html}` + + modifiedResponse.slice(headPosition); + } + } else if (inject.injectTo === "body") { + if (bodyPosition !== -1 || upperBody !== -1) { + modifiedResponse = + modifiedResponse.slice( + 0, + bodyPosition + ) + + `${inject.html}` + + modifiedResponse.slice(bodyPosition); + } + } + } + } + } responseCtx.body = ultraviolet.rewriteHtml( - await response.text(), + modifiedResponse, { document: true, injectHead: ultraviolet.createHtmlInject(