4

I am trying to execute javascript function inside my Angular2 file via component. But I can't get this working.

This is how my ts file looks like.

import { Component, OnInit, Input } from '@angular/core';
import {BrowserModule, DomSanitizer} from '@angular/platform-browser'

import { JavaScriptService } from './javascript.service';

@Component({
  selector: 'app-javascript',
  template: `
     <div [innerHtml]="html"></div>
  `
})
export class JavaScriptService{

  html: any;

  constructor(private sanitizer: DomSanitizer) {

  this.html = sanitizer.bypassSecurityTrustHtml(`<div><script type="text/javascript"> alert('h');</script></div>`);

  }

}

This is how html looks when Angular renders page in browser (I inspected elemens)

<div ng-reflect-inner-h-t-m-l="<div><script type=&quot;text/javascript&quot;> alert('h');</script></div>">
<div><script type="text/javascript"> alert('h');</script></div>
</div>

I don't understand why alert is not executing after page is loaded.

I have tried both with bypassSecurityTrustHtml and bypassSecurityTrustScript but no luck. I appreciate if anyone have solution for this.

Thank you!

Bunyamin Coskuner
  • 8,719
  • 1
  • 28
  • 48
Eldlabs
  • 523
  • 7
  • 19

1 Answers1

1

I've seen this done before in your .ts file.

It will execute your script tag.

const fragment = document.createRange().createContextualFragment(yourHtmlString); document.body.appendChild(fragment);

Even though it works, then I get this issue SafeValue must use [property]=binding: (see http://g.co/ng/security#xss) being appended to my page so I'm working on resolving that.

Karl
  • 1,743
  • 1
  • 15
  • 20