javascript / beginner
Snippet
Escaping Untrusted User Text to Prevent Cross-Site Scripting
Injecting unescaped user strings directly into web pages exposes applications to Cross-Site Scripting (XSS) attacks. By default, standard JavaScript string interpolation in Svelte treats input as plain text and encodes dangerous HTML characters, neutralizing injected scripts and protecting client-side security.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
<script>// String containing potentially malicious markuplet userProvidedComment = '<img src=x onerror="alert(1)"> Great post!';</script><!-- Safe: Standard interpolation escapes HTML automatically --><div class="comment-safe"><p>Safe comment: {userProvidedComment}</p></div><!-- Insecure alternative: Never render untrusted strings with {@html} --><!-- {@html userProvidedComment} -->
svelte
Breakdown
1
let userProvidedComment = '<img src=x onerror="alert(1)"> Great post!';
Defines a string variable simulating dangerous raw HTML input from an external user.
2
<p>Safe comment: {userProvidedComment}</p>
Renders the text safely by escaping special characters like angle brackets.
3
<!-- {@html userProvidedComment} -->
Highlights that raw HTML directives must never be used with unsanitized user content.