I have a variable test = '<script>alert()</script>'
.
I put this variable into Angular component using interpolation <div>{{ this.test }}</div>
.
Then it just displayed as plain text on the page like this: <script>alert("test")</script>
Questions:
- Why value not sanitized by Angular? (for example, for [innerHtml] it will remove "script" tags). From Angular docs: "When a value is inserted into the DOM from a template binding, or interpolation, Angular sanitizes and escapes untrusted values."
- If value not sanitized – why application doesn’t run the script?
2
Answers
Angular automatically sanitizes values to prevent cross site scripting. It will strip out unsafe code.
In some scenarios, it might be necessary to disable sanitization. For these use cases, Angular provides a DomSanitizer service that you can use to disable sanitization. Be sure to read up on XSS and the potential risks before using this service.
Two things here Interpoaltion and InnerHtml.
Interpolation can only be used to render plain text content, not HTML.
You should only use [innerHtml] when you trust the content source or have properly sanitized the data using the DomSanitizer service to prevent XSS attacks.
In your case, when you use interpolation
{{ this.test }}
to display the variable, Angular treats the value as plain text and does not perform any automatic sanitization, resulting in the<script>
tags being displayed as plain text on the page.On the other hand, when you use the
[innerHtml]
binding, Angular treats the value as HTML content and automatically sanitizes it using the DomSanitizer service to prevent any malicious scripts or potential security risks. This is why the<script>
tags are removed when using[innerHtml]
.If you want to display the content of the variable as HTML with proper sanitization, you should use the
[innerHtml]
binding and sanitize the value using the DomSanitizer service. Here’s an example of how you can do it in your component: