Angularでiframeを使ったページを作っているとき、iframeで表示させるページを動的に決定させようとすると、エラー"unsafe value used in a resource URL context"が出ることが有ります。
サンプルコード
import { Component } from '@angular/core';
import { DomSanitizer, SafeHtml} from '@angular/platform-browser';
@Component({
selector: 'my-app',
template: `<iframe [src]="url"></iframe>`,
})
export class AppComponent {
url = "http://www.tohoho-web.com/";
}
エラーメッセージ
上記のコードを実行すると、ブラウザのconsole出力に以下のエラーが出ます。
ERROR Error: unsafe value used in a resource URL context (see http://g.co/ng/security#xss)
at DomSanitizerImpl.sanitize (dom_sanitization_service.ts:209)
at setElementProperty (ng_content.ts:1)
at checkAndUpdateElementValue (element.ts:318)
at checkAndUpdateElementInline (element.ts:213)
at checkAndUpdateNodeInline (view.ts:486)
at checkAndUpdateNode (view.ts:431)
at debugCheckAndUpdateNode (services.ts:237)
at debugCheckRenderNodeFn (services.ts:330)
at Object.eval [as updateRenderer] (AppComponent.html:9)
at Object.debugUpdateRenderer [as updateRenderer] (services.ts:309)
これは、Angulerの機能でクロスサイトスクリプティング(XSS脆弱性)を回避するための機能です。
解決方法
この問題を解決するには、以下のようにSafeResourceUrlを使用すればよいです。
import { Component } from '@angular/core';
import { DomSanitizer, SafeResourceUrl} from '@angular/platform-browser';
@Component({
selector: 'my-app',
template: `<iframe [src]="trustUrl"></iframe>`,
})
export class AppComponent {
url = "http://www.tohoho-web.com/";
trustUrl: SafeResourceUrl;
constructor(private sanitizer: DomSanitizer) {
this.trustUrl = sanitizer.bypassSecurityTrustResourceUrl(this.url);
}
}
こちらもおススメ