[angular] <img> : 리소스 URL 컨텍스트에서 사용되는 안전하지 않은 값

최신 Angular 2 릴리스 후보로 업그레이드 한 이후로 내 img태그 :

<img class='photo-img' [hidden]="!showPhoto1" src='{{theMediaItem.photoURL1}}'>

브라우저 오류가 발생합니다.

ORIGINAL EXCEPTION : 오류 : 리소스 URL 컨텍스트에 사용 된 안전하지 않은 값

URL의 값은 다음과 같습니다.

http://veeu-images.s3.amazonaws.com/media/userphotos/116_1464645173408_cdv_photo_007.jpg

편집하다:

이 질문이 중복되어야한다는 다른 솔루션의 제안을 시도했지만 동일한 오류가 발생합니다.

컨트롤러에 다음 코드를 추가했습니다.

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

@Component({
  templateUrl: 'build/pages/veeu/veeu.html'
})
export class VeeUPage {
  static get parameters() {
    return [[NavController], [App], [MenuController], [DomSanitizationService]];
  }

  constructor(nav, app, menu, sanitizer) {

    this.app = app;
    this.nav = nav;
    this.menu = menu;
    this.sanitizer = sanitizer;

    this.theMediaItem.photoURL1 = this.sanitizer.bypassSecurityTrustUrl(this.mediaItems[1].url);
  }

여전히 동일한 오류 메시지가 나타납니다.

EDIT2 :

또한 html을 다음과 같이 변경했습니다.

<img class='photo-img' [hidden]="!showPhoto1" [src]='theMediaItem.photoURL1'>

여전히 동일한 오류 메시지가 나타납니다.



답변

rc.4를 사용하고 있으며이 방법은 ES2015 (ES6)에서 작동합니다.

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

@Component({
  templateUrl: 'build/pages/veeu/veeu.html'
})
export class VeeUPage {
  static get parameters() {
    return [NavController, App, MenuController, DomSanitizationService];
  }

  constructor(nav, app, menu, sanitizer) {

    this.app = app;
    this.nav = nav;
    this.menu = menu;
    this.sanitizer = sanitizer;
  }

  photoURL() {
    return this.sanitizer.bypassSecurityTrustUrl(this.mediaItems[1].url);
  }
}

HTML에서 :

<iframe [src]='photoURL()' width="640" height="360" frameborder="0"
    webkitallowfullscreen mozallowfullscreen allowfullscreen>
</iframe>

함수를 사용하면 삭제 한 후에도 값이 변경되지 않습니다. 또한 사용하는 삭제 기능은 컨텍스트에 따라 다릅니다.

이미지의 경우 bypassSecurityTrustUrl작동하지만 다른 용도의 경우 문서를 참조해야합니다 .

https://angular.io/docs/ts/latest/api/platform-browser/index/DomSanitizer-class.html


답변

파이프

// Angular
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';

/**
 * Sanitize HTML
 */
@Pipe({
  name: 'safe'
})
export class SafePipe implements PipeTransform {
  /**
   * Pipe Constructor
   *
   * @param _sanitizer: DomSanitezer
   */
  // tslint:disable-next-line
  constructor(protected _sanitizer: DomSanitizer) {
  }

  /**
   * Transform
   *
   * @param value: string
   * @param type: string
   */
  transform(value: string, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
    switch (type) {
      case 'html':
        return this._sanitizer.bypassSecurityTrustHtml(value);
      case 'style':
        return this._sanitizer.bypassSecurityTrustStyle(value);
      case 'script':
        return this._sanitizer.bypassSecurityTrustScript(value);
      case 'url':
        return this._sanitizer.bypassSecurityTrustUrl(value);
      case 'resourceUrl':
        return this._sanitizer.bypassSecurityTrustResourceUrl(value);
      default:
        return this._sanitizer.bypassSecurityTrustHtml(value);
    }
  }
}

주형

{{ data.url | safe:'url' }}

그게 다야!

참고 : 필요하지 않지만 다음은 파이프의 구성 요소 사용입니다.

  // Public properties
  itsSafe: SafeHtml;

  // Private properties
  private safePipe: SafePipe = new SafePipe(this.domSanitizer);

  /**
   * Component constructor
   *
   * @param safePipe: SafeHtml
   * @param domSanitizer: DomSanitizer
   */
  constructor(private safePipe: SafePipe, private domSanitizer: DomSanitizer) {
  }

  /**
   * On init
   */
  ngOnInit(): void {
    this.itsSafe = this.safePipe.transform('<h1>Hi</h1>', 'html');
  }


답변

이 문제를 해결하는 가장 우아한 방법은 파이프를 사용하는 것입니다. 여기에 예 (내 블로그)가 있습니다. 따라서 url | safe파이프를 사용 하여 보안을 우회 할 수 있습니다 .

<iframe [src]="url | safe"></iframe>

자세한 내용은 npm의 문서를 참조하십시오 : https://www.npmjs.com/package/safe-pipe


답변

안전 파이프를 사용하여 수정하십시오.

  • 없는 경우 안전한 파이프를 만듭니다.

    ng gc 파이프 안전

  • app.module.ts에 안전 파이프 추가

    선언 : [SafePipe]

  • 당신의 TS에 안전한 파이프를 선언하십시오

Dom Sanitizer 및 Safe Pipe를 가져와 URL에 안전하게 액세스

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

@Pipe({ name: 'safe' })

export class SafePipe implements PipeTransform {

constructor(private sanitizer: DomSanitizer) { }
transform(url) {
 return this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }
}

-src URL로 안전 추가

<iframe width="900" height="500" [src]="link | safe"/>


답변

새니 타이 저를 뷰에 노출하거나 호출을 bypassSecurityTrustUrl로 전달하는 메서드를 노출 할 수 있습니다.

<img class='photo-img' [hidden]="!showPhoto1"
    [src]='sanitizer.bypassSecurityTrustUrl(theMediaItem.photoURL1)'>


답변

Angular는 기본적으로 모든 값을 신뢰할 수없는 것으로 처리합니다. 속성, 속성, 스타일, 클래스 바인딩 또는 보간을 통해 템플릿에서 DOM에 값이 삽입되면 Angular는 신뢰할 수없는 값을 삭제하고 이스케이프합니다.

따라서 DOM을 직접 조작하고 콘텐츠를 삽입하는 경우이를 삭제해야합니다. 그렇지 않으면 Angular에서 오류가 발생합니다.

나는 이것을 위해 SanitizeUrlPipe 파이프를 만들었습니다.

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

@Pipe({
    name: "sanitizeUrl"
})
export class SanitizeUrlPipe implements PipeTransform {

    constructor(private _sanitizer: DomSanitizer) { }

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

그리고 이것은 당신이 사용할 수있는 방법입니다

<iframe [src]="url | sanitizeUrl" width="100%" height="500px"></iframe>

HTML을 추가하려면 SanitizeHtmlPipe 가 도움이 될 수 있습니다.

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

@Pipe({
    name: "sanitizeHtml"
})
export class SanitizeHtmlPipe implements PipeTransform {

    constructor(private _sanitizer: DomSanitizer) { }

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

여기에서 각도 보안에 대해 자세히 알아보십시오 .


답변

일반적 safe pipe으로 다음과 같이 별도의 재사용 가능한 구성 요소를 추가합니다.

# Add Safe Pipe

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

@Pipe({name: 'mySafe'})
export class SafePipe implements PipeTransform {
    constructor(private sanitizer: DomSanitizer) {
    }

    public transform(url) {
        return this.sanitizer.bypassSecurityTrustResourceUrl(url);
    }
}
# then create shared pipe module as following

import { NgModule } from '@angular/core';
import { SafePipe } from './safe.pipe';
@NgModule({
    declarations: [
        SafePipe
    ],
    exports: [
        SafePipe
    ]
})
export class SharedPipesModule {
}
# import shared pipe module in your native module

@NgModule({
    declarations: [],
    imports: [
        SharedPipesModule,
    ],
})
export class SupportModule {
}
<!-------------------
call your url (`trustedUrl` for me) and add `mySafe` as defined in Safe Pipe
---------------->
<div class="container-fluid" *ngIf="trustedUrl">
    <iframe [src]="trustedUrl | mySafe" align="middle" width="100%" height="800" frameborder="0"></iframe>
</div>