summaryrefslogtreecommitdiffstatshomepage
path: root/src/htmx.js
diff options
context:
space:
mode:
authorCarson Gross <carson@bigsky.software>2024-03-13 18:11:58 -0600
committerCarson Gross <carson@bigsky.software>2024-03-13 18:11:58 -0600
commitef791c51ebf6407ebc757df84b9f695b9f6930dc (patch)
tree82edd3935ab30de703a8fd65a1f93fea982955af /src/htmx.js
parent83e939a3709c8752a88c1349ce0894dee6f7bf6f (diff)
downloadhtmx-ef791c51ebf6407ebc757df84b9f695b9f6930dc.tar.gz
htmx-ef791c51ebf6407ebc757df84b9f695b9f6930dc.zip
fix double script execution issue when using template parsing
Diffstat (limited to 'src/htmx.js')
-rw-r--r--src/htmx.js33
1 files changed, 25 insertions, 8 deletions
diff --git a/src/htmx.js b/src/htmx.js
index 20f4095e..b9fc4b06 100644
--- a/src/htmx.js
+++ b/src/htmx.js
@@ -309,10 +309,24 @@ return (function () {
content = content.replace(HEAD_TAG_REGEX, '');
}
if (htmx.config.useTemplateFragments && partialResponse) {
- var documentFragment = parseHTML("<body><template>" + content + "</template></body>", 0);
+ var fragment = parseHTML("<body><template>" + content + "</template></body>", 0);
// @ts-ignore type mismatch between DocumentFragment and Element.
// TODO: Are these close enough for htmx to use interchangeably?
- return documentFragment.querySelector('template').content;
+ if (htmx.config.allowScriptTags) {
+ // if there is a nonce set up, set it on the new script tags
+ forEach(fragment.querySelectorAll("script"), function (script) {
+ if (htmx.config.inlineScriptNonce) {
+ script.nonce = htmx.config.inlineScriptNonce;
+ }
+ getInternalData(script).executed = true; // mark as executed due to template insertion semantics
+ })
+ } else {
+ forEach(fragment.querySelectorAll("script"), function (script) {
+ // remove all script tags if scripts are disabled
+ removeElement(script);
+ })
+ }
+ return fragment.querySelector('template').content;
}
switch (startTag) {
case "thead":
@@ -1892,7 +1906,8 @@ return (function () {
}
function evalScript(script) {
- if (htmx.config.allowScriptTags && (script.type === "text/javascript" || script.type === "module" || script.type === "") ) {
+ if (!getInternalData(script).executed && htmx.config.allowScriptTags &&
+ (script.type === "text/javascript" || script.type === "module" || script.type === "") ) {
var newScript = getDocument().createElement("script");
forEach(script.attributes, function (attr) {
newScript.setAttribute(attr.name, attr.value);
@@ -1918,12 +1933,14 @@ return (function () {
}
function processScripts(elt) {
- if (matches(elt, "script")) {
- evalScript(elt);
+ if (!htmx.config.useTemplateFragments) {
+ if (matches(elt, "script")) {
+ evalScript(elt);
+ }
+ forEach(findAll(elt, "script"), function (script) {
+ evalScript(script);
+ });
}
- forEach(findAll(elt, "script"), function (script) {
- evalScript(script);
- });
}
function shouldProcessHxOn(elt) {