Skip to content

Commit e521b9d

Browse files
authored
evaluate script tags when replacing html (#3826)
1 parent 4bfdafb commit e521b9d

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

apps/dashboard/app/javascript/turbo_shim.js

+3-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
this shim until we enable it.
66
*/
77

8+
import { setInnerHTML } from './utils';
9+
810
export function replaceHTML(id, html) {
911
const ele = document.getElementById(id);
1012

@@ -16,7 +18,7 @@ export function replaceHTML(id, html) {
1618
const newHTML = tmp.querySelector('template').innerHTML;
1719
tmp.remove();
1820

19-
ele.innerHTML = newHTML;
21+
setInnerHTML(ele, newHTML);
2022
}
2123
}
2224

apps/dashboard/app/javascript/utils.js

+22
Original file line numberDiff line numberDiff line change
@@ -80,3 +80,25 @@ export function openLinkInJs(event) {
8080
mainDiv.prepend(alertDiv);
8181
}
8282
}
83+
84+
// Helper method to set an element's innerHTML property
85+
// and evaluate any <script> tags that may exist within it.
86+
// Just setting innerHTML of an html element does not re-evaluate
87+
// the <script> tags that it may hold.
88+
export function setInnerHTML(element, html) {
89+
element.innerHTML = html;
90+
const scripts = Array.from(element.querySelectorAll("script"));
91+
92+
scripts.forEach(currentElement => {
93+
const newElement = document.createElement("script");
94+
95+
Array.from(currentElement.attributes).forEach( attr => {
96+
newElement.setAttribute(attr.name, attr.value);
97+
});
98+
99+
const scriptText = document.createTextNode(currentElement.innerHTML);
100+
newElement.appendChild(scriptText);
101+
102+
currentElement.parentNode.replaceChild(newElement, currentElement);
103+
});
104+
}

0 commit comments

Comments
 (0)