aboutsummaryrefslogtreecommitdiff
path: root/lume/src/notes/2024/slash-script-in-string.mdx
diff options
context:
space:
mode:
authorXe Iaso <me@xeiaso.net>2024-02-03 20:19:40 -0500
committerXe Iaso <me@xeiaso.net>2024-02-03 20:19:40 -0500
commitc455de447df2686541c5c26c5d7d6ee52265725a (patch)
tree33f499e2412b380c5ab881b3295ad31a3d37f554 /lume/src/notes/2024/slash-script-in-string.mdx
parent944fbf678403c77e158accd66363accbbe6d6eb4 (diff)
downloadxesite-c455de447df2686541c5c26c5d7d6ee52265725a.tar.xz
xesite-c455de447df2686541c5c26c5d7d6ee52265725a.zip
notes/2024: add moment of discovery about inline JavaScript code in HTML
Signed-off-by: Xe Iaso <me@xeiaso.net>
Diffstat (limited to 'lume/src/notes/2024/slash-script-in-string.mdx')
-rw-r--r--lume/src/notes/2024/slash-script-in-string.mdx52
1 files changed, 52 insertions, 0 deletions
diff --git a/lume/src/notes/2024/slash-script-in-string.mdx b/lume/src/notes/2024/slash-script-in-string.mdx
new file mode 100644
index 0000000..85848b4
--- /dev/null
+++ b/lume/src/notes/2024/slash-script-in-string.mdx
@@ -0,0 +1,52 @@
+---
+title: "TIL: you need to escape the </script> in a string in an inline script in HTML"
+date: 2024-02-03
+type: blog
+hero:
+ ai: "Photo by Xe Iaso, iPhone 13 Pro"
+ file: winter-drive
+ prompt: "A color-graded image of a snowy field taken from the side of a moving car."
+---
+
+When I was implementing [this change](https://github.com/Xe/site/commit/944fbf678403c77e158accd66363accbbe6d6eb4) in my site, I ran into a weird issue where my literal JavaScript text was being inserted into the page as if it was in the literal HTML. This was odd at first, but then I realized what was going on.
+
+I was converting code that looked like this:
+
+```html
+<script src="https://ethical-ads.whatever/script.js" async></script>
+<div
+ data-ea-publisher="christinewebsite"
+ data-ea-type="text"
+ data-ea-style="fixedfooter"
+></div>
+```
+
+Into something like this:
+
+```html
+<script>
+ if (!window.location.hostname.includes(".shark-harmonic.ts.net")) {
+ document.write('<script src="https://ethical-ads.whatever/script.js" async></script>');
+ }
+</script>
+<div data-ea-publisher="christinewebsite" data-ea-type="text" data-ea-style="fixedfooter"></div>
+```
+
+But then I saw `'); }` at the top of every page. This was odd, but when I figured out what was going on, I felt very dumb. I was writing a string that contained a `</script>` tag, which was causing the browser to think that the script tag was ending early.
+
+The fix was simple: escape the `</script>` tag in the string. This is done by replacing the `/` with `\/`:
+
+```html
+<script>
+ if (!window.location.hostname.includes(".shark-harmonic.ts.net")) {
+ document.write(
+ '<script src="https://ethical-ads.whatever/script.js" async><\/script>'
+ );
+ }
+</script>
+<div
+ data-ea-publisher="christinewebsite"
+ data-ea-type="text"
+ data-ea-style="fixedfooter"
+></div>
+```