The code and data behind xeiaso.net
5
fork

Configure Feed

Select the types of activity you want to include in your feed.

notes/2024: add moment of discovery about inline JavaScript code in HTML

Signed-off-by: Xe Iaso <me@xeiaso.net>

Xe Iaso c455de44 944fbf67

+52
+52
lume/src/notes/2024/slash-script-in-string.mdx
··· 1 + --- 2 + title: "TIL: you need to escape the </script> in a string in an inline script in HTML" 3 + date: 2024-02-03 4 + type: blog 5 + hero: 6 + ai: "Photo by Xe Iaso, iPhone 13 Pro" 7 + file: winter-drive 8 + prompt: "A color-graded image of a snowy field taken from the side of a moving car." 9 + --- 10 + 11 + 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. 12 + 13 + I was converting code that looked like this: 14 + 15 + ```html 16 + <script src="https://ethical-ads.whatever/script.js" async></script> 17 + <div 18 + data-ea-publisher="christinewebsite" 19 + data-ea-type="text" 20 + data-ea-style="fixedfooter" 21 + ></div> 22 + ``` 23 + 24 + Into something like this: 25 + 26 + ```html 27 + <script> 28 + if (!window.location.hostname.includes(".shark-harmonic.ts.net")) { 29 + document.write('<script src="https://ethical-ads.whatever/script.js" async></script>'); 30 + } 31 + </script> 32 + <div data-ea-publisher="christinewebsite" data-ea-type="text" data-ea-style="fixedfooter"></div> 33 + ``` 34 + 35 + 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. 36 + 37 + The fix was simple: escape the `</script>` tag in the string. This is done by replacing the `/` with `\/`: 38 + 39 + ```html 40 + <script> 41 + if (!window.location.hostname.includes(".shark-harmonic.ts.net")) { 42 + document.write( 43 + '<script src="https://ethical-ads.whatever/script.js" async><\/script>' 44 + ); 45 + } 46 + </script> 47 + <div 48 + data-ea-publisher="christinewebsite" 49 + data-ea-type="text" 50 + data-ea-style="fixedfooter" 51 + ></div> 52 + ```