Skip to content

Commit 4604744

Browse files
committed
Cloudflare Worker: allow injecting a user JavaScript file
Related readthedocs/readthedocs.org#11758
1 parent 594de44 commit 4604744

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

packages/addons-inject/index.js

+14-2
Original file line numberDiff line numberDiff line change
@@ -140,12 +140,14 @@ async function transformResponse(response) {
140140
const injectHostingIntegrations =
141141
headers.get("x-rtd-hosting-integrations") || "false";
142142
const forceAddons = headers.get("x-rtd-force-addons") || "false";
143+
const userJsFile = headers.get("x-rtd-user-js-file") || "";
143144
const httpStatus = response.status;
144145

145146
// Log some debugging data
146147
console.log(`ContentType: ${contentType}`);
147148
console.log(`X-RTD-Force-Addons: ${forceAddons}`);
148149
console.log(`X-RTD-Hosting-Integrations: ${injectHostingIntegrations}`);
150+
console.log(`X-RTD-User-Js-File: ${userJsFile}`);
149151
console.log(`HTTP status: ${httpStatus}`);
150152

151153
// Debug mode for some test cases. This is just for triggering an exception
@@ -191,7 +193,7 @@ async function transformResponse(response) {
191193
// rewriter.on(readthedocsData, new removeElement())
192194

193195
rewriter
194-
.on("head", new addPreloads())
196+
.on("head", new addPreloads(userJsFile))
195197
.on(
196198
"head",
197199
new addMetaTags(
@@ -227,7 +229,7 @@ async function transformResponse(response) {
227229
//
228230
if (forceAddons === "false" && injectHostingIntegrations === "true") {
229231
return new HTMLRewriter()
230-
.on("head", new addPreloads())
232+
.on("head", new addPreloads(userJsFile))
231233
.on(
232234
"head",
233235
new addMetaTags(projectSlug, versionSlug, resolverFilename, httpStatus),
@@ -267,9 +269,19 @@ class removeElement {
267269
}
268270

269271
class addPreloads {
272+
constructor(userJsFile) {
273+
this.userJsFile = userJsFile;
274+
}
275+
270276
element(element) {
271277
console.log("addPreloads");
272278
element.append(AddonsConstants.scriptAddons, { html: true });
279+
280+
if (this.userJsFile) {
281+
console.log("Adding userJsFile");
282+
const userJsFileTag = `<script async type="text/javascript" src="${this.userJsFile}"></script>`;
283+
element.append(userJsFileTag, { html: true });
284+
}
273285
}
274286
}
275287

0 commit comments

Comments
 (0)