( html: string, headScripts: readonly string[], bodyScripts: readonly string[], stripEmbeddedRuntime = true, )
| 187 | } |
| 188 | |
| 189 | export function injectScriptsIntoHtml( |
| 190 | html: string, |
| 191 | headScripts: readonly string[], |
| 192 | bodyScripts: readonly string[], |
| 193 | stripEmbeddedRuntime = true, |
| 194 | ): string { |
| 195 | if (stripEmbeddedRuntime) { |
| 196 | html = stripEmbeddedRuntimeScripts(html); |
| 197 | } |
| 198 | |
| 199 | if (headScripts.length > 0) { |
| 200 | const headTags = inlineScriptTags(headScripts); |
| 201 | if (html.includes("</head>")) { |
| 202 | // Function replacement avoids `$&` interpolation in runtime source. |
| 203 | html = html.replace("</head>", () => `${headTags}\n</head>`); |
| 204 | } else if (html.includes("<body")) { |
| 205 | html = html.replace("<body", () => `${headTags}\n<body`); |
| 206 | } else { |
| 207 | html = `${headTags}\n${html}`; |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | if (bodyScripts.length > 0) { |
| 212 | const bodyTags = inlineScriptTags(bodyScripts); |
| 213 | if (html.includes("</body>")) { |
| 214 | html = html.replace("</body>", () => `${bodyTags}\n</body>`); |
| 215 | } else { |
| 216 | html = `${html}\n${bodyTags}`; |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | return html; |
| 221 | } |
no test coverage detected