Search code examples
javascriptangularangular15angular-dom-sanitizer

Santitize script src url value angular provides incorrect url value


I need to sanitize the external url value to dynamically load script and remove script for specific component alone.

used following approch

private getUrl(): SafeResourceUrl {
    // declared value in environment file   
   return this.sanitizer.bypassSecurityTrustResourceUrl(env.externalUrl);
  } 

public loadScript(): void {
    const scriptele= this.renderer.createElement('script');
    this.renderer.setProperty(scriptele, 'src', this.getUrl());
    this.renderer.appendChild(document.head, scriptele);
  }

I am expecting the correct script to be called in head section like <script src="https://urlvalue.min.js"></script> // like this

but it gives as following with some extra text <script src="SafeValue must use [property]=binding: https://urlvalue.min.js (see https://g.co/ng/security#xss)"></script>


Solution

  • Try with sanitize method with SecurityContext instead:

    this.sanitizer.sanitize(SecurityContext.URL, env.externalUrl)
    

    code:

      const scriptele= this.renderer.createElement('script');
      this.renderer.setProperty(scriptele, 'src', this.sanitizer.sanitize(SecurityContext.URL, env.externalUrl));
      this.renderer.appendChild(document.head, scriptele);