skip to Main Content

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:

  1. 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."
  2. If value not sanitized – why application doesn’t run the script?

2

Answers


  1. 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.

    Login or Signup to reply.
  2. Two things here Interpoaltion and InnerHtml.

    Interpolation can only be used to render plain text content, not HTML.

    Example: <p>Hello, {{ name }}!</p>

    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.

    Example: <div [innerHtml]="htmlContent"></div>

    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:

    import { Component, OnInit } from '@angular/core';
    import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
    
    @Component({
      selector: 'app-your-component',
      template: '<div [innerHtml]="sanitizedTest"></div>'
    })
    export class YourComponent implements OnInit {
      test = '<script>alert("test")</script>';
      sanitizedTest: SafeHtml;
    
      constructor(private sanitizer: DomSanitizer) { }
    
      ngOnInit() {
        // Sanitize the value before binding it to the template
        this.sanitizedTest = this.sanitizer.bypassSecurityTrustHtml(this.test);
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search