[FIX] playground: correctly escape backslashes and interpolation sigils

Previously, if you used a backslash in a template on the playground, it
would be interpreted as an escape sequence, and if you wrote "${" it
would likely crash, as it would be treated as an interpolation sigil in
the context of the script element injected inside the playground's
iframe.

A previous fix already escaped backticks, this commit completes the
escaping by escaping the two other things that have special meaning
within template literals.
This commit is contained in:
Samuel Degueldre
2024-05-13 15:21:43 +02:00
committed by Géry Debongnie
parent 11e4e67599
commit 7952f31e63
+2 -3
View File
@@ -41,9 +41,6 @@ const loadFile = (path) => {
* Make an iframe, with all the js, css and xml properly injected. * Make an iframe, with all the js, css and xml properly injected.
*/ */
function makeCodeIframe(js, css, xml) { function makeCodeIframe(js, css, xml) {
// escape backticks in the xml so they don't close the template string
const escapedXml = xml.replace(/`/g, '\\\`');
const iframe = document.createElement("iframe"); const iframe = document.createElement("iframe");
iframe.onload = () => { iframe.onload = () => {
const doc = iframe.contentDocument; const doc = iframe.contentDocument;
@@ -55,6 +52,8 @@ function makeCodeIframe(js, css, xml) {
const script = doc.createElement("script"); const script = doc.createElement("script");
script.type = "module"; script.type = "module";
// escape characters with special meaning in template literals
const escapedXml = xml.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$\{/, "\\${");
script.textContent = `const TEMPLATES = \`${escapedXml}\`\n${js}`; script.textContent = `const TEMPLATES = \`${escapedXml}\`\n${js}`;
doc.body.appendChild(script); doc.body.appendChild(script);