javascript / beginner
Snippet
Preventing Cross-Site Scripting with Svelte Automatic Text Escaping
To safeguard applications against Cross-Site Scripting (XSS) attacks, Svelte automatically escapes HTML entities inside standard template expressions ({variable}). This ensures that potentially malicious HTML tags or script injection attempts are treated strictly as harmless plain text.
snippet.js
javascript
1
2
3
4
5
6
7
8
<script>let untrustedInput = "<img src='invalid' onerror='alert(1)'> Hello & welcome!";</script><!-- Standard curly braces safely escape raw strings into plain text --><div class="comment-body">{untrustedInput}</div>
svelte
Breakdown
1
let untrustedInput = "<img src='invalid' onerror='alert(1)'> Hello & welcome!";
Stores an untrusted string containing potential XSS markup.
2
{untrustedInput}
Renders the text safely by escaping markup characters into standard text nodes.