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!

3
  • 6
    AFAIK script tags can't be added using innerHTML. See stackoverflow.com/questions/38088996/… for how to add a script tag. Commented Mar 16, 2017 at 7:40
  • I also need help on this. Commented Apr 15, 2017 at 6:41
  • 1
    did this get resolved? Commented Jul 26, 2017 at 21:46

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.