Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

html - Inject <input> in innerHTML angular 2

I am trying to inject a input HTML tag with Angular 2, here is my project :

    <div [innerHTML]="inputpdf"></div>

The .ts :

export class FaxSendComponent  {
     inputpdf = '<input type="text" name="fname">';
     }

Here is the log from the console :

WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss).

I try with other html tag like <h3> and it works perfectly.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should trust the HTML first before injecting it. You have to use the DomSanitizer for such a thing. An <h3> element is considered safe. An <input> element is not.

Change your FaxSendComponent to something like this:

export class FaxSendComponent  {

    private _inputpdf: string = '<input type="text" name="fname">';

    public get inputpdf() : SafeHtml {
       return this._sanitizer.bypassSecurityTrustHtml(this._inputpdf);
    }

    constructor(private _sanitizer: DomSanitizer){}
}

And have your template stay the same as this:

<div [innerHTML]="inputpdf"></div>

A little heads-up though:

WARNING: calling this method with untrusted user data exposes your application to XSS security risks!

If you plan on using this technique more, you can try to write a Pipe to fulfil this task.

@Pipe({
    name: 'sanitizeHtml'
})
export class SanitizeHtml implements PipeTransform  {

   constructor(private _sanitizer: DomSanitizer){}  

   transform(v: string) : SafeHtml {
      return this._sanitizer.bypassSecurityTrustHtml(v); 
   } 
} 

If you have a pipe like this, your FaxSendComponent will change to this:

@Component({
   selector: 'fax-send',
   template: `<div [innerHTML]="inputpdf | sanitizeHtml"></div>`
})
export class FaxSendComponent  {

    public inputpdf: string = '<input type="text" name="fname">';

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...