问题
I have tried using DomSanitizer methods to sanitize the following type of url with no success
C:\path\to\executable
Is there any way to sanitize this url to be used as href value?
Also I am binding the value with [] notation so I am sure it is not interpolated as string.
回答1:
First the url should be C:/path/to/executable
not the one C:\path\to\executable
According to http://www.ietf.org/rfc/rfc2396.txt backslash characters are not valid characters in URLs
Most of the browsers convert the backslash into forward slashes. Technically, if you required backslash characters in your URL you need to encode them using %5C.
Now about the sanitization
You could just bind a function that returns safe url using bypassSecurityTrustUrl()
in angular DomSanitizer
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");
}
}
Recommended
Using Pipe: You can create a pipe to disable Angular’s built-in sanitization
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}`);
}
}
}
NOTE : Don't forget to inject this pipe service in your app.module.ts
import { SafePipe } from './shared/safe-url.pipe';
@NgModule({ declarations: [SafePipe],...});
Now you can use the pipe to disable the built-in sanitization
<a [href]="'C:/path/to/executable' | safe: 'url'"> link </a>
I would recommend using pipe as the code is reusable , also here is the working demo : https://stackblitz.com/edit/angular-vxcvfr
回答2:
I have used it like this:
In ts file.
import { DomSanitizer } from '@angular/platform-browser';
constructor(
public domSanitizer: DomSanitizer
) { }
in HTML file
<img [src]="domSanitizer.bypassSecurityTrustUrl(pazar.imagedata)" class="zoom">
来源:https://stackoverflow.com/questions/53222357/angular-6-sanitize-local-drive-url