Angular sanitizer - exception for YouTube iframe

Viewed 1359

I have an API that returns HTML code (which contains iframe object).

The code that is sent to client looks like this:

<p>Something blabla</p>
<iframe allowfullscreen="true" frameborder="0" height="270" src="https://www.youtube.com/embed/someID?feature=oembed" width="480"></iframe>

Now, how can I add an exception to sanitizer only for YouTube? The problem is, the HTML code is user input (not fully user input, but only to people I trust, so I guess there is no security risk), so I can't use bypassSecurityTrustResourceUrl, right?

My code (page.component.ts)

constructor(private _router: Router, private _http: Http, private _sanitizer: DomSanitizer) {
    this.fetchNews();
}

fetchNews() {
    this._http
      .get(this.urlAPI)
      .map((response: Response) => {
        let json = response.json();
        this.content = json.results[0].content;
      }).subscribe();
}

And HTML (page.component.html):

<div [innerHTML]="content">
</div>
1 Answers

simply need to create a pipe using cli

ionic g pipe Youtube

then import domsanatizer in pipe file

import { DomSanitizer } from '@angular/platform-browser';

import pipe in app.module.ts

import {Youtube } from '../pipes/youtube';

then declare pipe in declarations

see below youtube.ts pipe file

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

/**
 * Generated class for the Youtube pipe.
 *
 * See https://angular.io/docs/ts/latest/guide/pipes.html for more info on
 * Angular Pipes.
 */
@Pipe({
  name: 'youtube',
})
export class Youtube implements PipeTransform {
  constructor (private dom:DomSanitizer) {

  }
  transform(value: string, args) {
    return this.dom.bypassSecurityTrustHtml(value);
  }
}

Last step in your html code :

<div [innerHTML]="content | youtube">
</div>
Related