DomSanitizerメソッドを使用して次のタイプのURLをサニタイズしようとしましたが、成功しませんでした
C:\path\to\executable
このURLをサニタイズしてhref値として使用する方法はありますか?
また、値を[]表記でバインドしているので、文字列として補間されていないと確信しています。
まず、URLはC:/path/to/executable
1つであってはなりませんC:\path\to\executable
http://www.ietf.org/rfc/rfc2396.txtによると、バックスラッシュ文字はURLの有効な文字ではありません
ほとんどのブラウザは、円記号を円記号に変換します。技術的には、URLに円記号が必要な場合は、%5Cを使用してそれらをエンコードする必要があります。
さて、消毒について
bypassSecurityTrustUrl()
Angular DomSanitizerで使用して、安全なURLを返す関数をバインドするだけです。
app.component.html
<a [href]="getlink()"> link </a>
app.component.ts
import { DomSanitizer} from '@angular/platform-browser';
export class AppComponent {
constructor(private sanitizer:DomSanitizer) { }
name = 'Angular';
getlink():SafeUrl {
return this.sanitizer.bypassSecurityTrustUrl("C:/path/to/executable");
}
}
推奨
パイプの使用:パイプを作成して、Angularの組み込みのサニタイズを無効にすることができます
safe.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';
@Pipe({
name: 'safe'
})
export class SafePipe implements PipeTransform {
constructor(protected sanitizer: DomSanitizer) {}
public transform(value: any, 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: throw new Error(`Invalid safe type specified: ${type}`);
}
}
}
注:このパイプサービスをapp.module.tsに挿入することを忘れないでください
import { SafePipe } from './shared/safe-url.pipe';
@NgModule({ declarations: [SafePipe],...});
これで、パイプを使用して組み込みのサニタイズを無効にできます
<a [href]="'C:/path/to/executable' | safe: 'url'"> link </a>
コードは再利用可能であるため、パイプを使用することをお勧めします。また、作業デモもあります:https://stackblitz.com/edit/angular-vxcvfr
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加