作者:文民左 | 来源:互联网 | 2022-11-30 12:19
我已经尝试使用DomSanitizer方法来清理以下类型的url但没有成功
C:\path\to\executable
有没有办法清理这个url用作href值?
我也用[]表示法绑定值,所以我确信它不是作为字符串插入的.
1> Joel Joseph..:
首先,网址应该C:/path/to/executable
不是那个 网址C:\path\to\executable
根据http://www.ietf.org/rfc/rfc2396.txt,反斜杠字符在URL中不是有效字符
大多数浏览器将反斜杠转换为正斜杠.从技术上讲,如果您在URL中需要反斜杠字符,则需要使用%5C对它们进行编码.
现在关于消毒
你可以绑定一个bypassSecurityTrustUrl()
在angular DomSanitizer中使用返回安全url的函数
app.component.html
link
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],...});
现在您可以使用管道禁用内置清理
link
我建议使用管道,因为代码是可重用的,这里也是工作演示:https://stackblitz.com/edit/angular-vxcvfr