I am trying to sanitize a pdf url and want to assign it to a string type variable so that I can use it for pdf viewer. Is there any way to do that?
If I use any type for pdfSrc type, I am getting Invalid parameter object: need either .data, .range or .url in the <pdf-viewer>.
Note: The URL which I used is for reference purpose, i would use external URLs in that place
landingpage.component.ts
import { DomSanitizer, SafeResourceUrl, SafeUrl } from '@angular/platform-browser';
export class LandingpageComponent implements OnInit {
public pdfSrc: string;
}
constructor(
private sanitizer: DomSanitizer) {
}
fnOpenAsset() {
let url = 'http://localhost/pdf_viewer-master/18/docs/pdf.pdf';
this.pdfSrc = this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
landingpage.component.html
<pdf-viewer class="alignComponentCenter" [src]="pdfSrc"
</pdf-viewer>
SafeResourceUrllink interface. Marker interface for a value that's safe to use as a URL to load executable code from.
bypassSecurityTrustHtml()linkBypass security and trust the given value to be safe HTML. Only use this when the bound HTML is unsafe (e.g. contains <script> tags) and the code should be executed.
SafeUrllinkMarker interface for a value that's safe to use as a URL linking to a document.
There are efforts from the angular team to make the usage of Safe* types more flexible. As far as I understand issue #33028 on the angular github page they are currently enabling the direct use of Safe* types as string. That way you could be using bypassSecurityTrustResourceUrl() and directly assign the return value to the src property. Excactly as @Muthu tried it initially.
this.pdfSrc = this.sanitizer.bypassSecurityTrustResourceUrl(url);
This would affect the following types (as they all extend the SafeValue interface):
SafeHtmlSafeUrlSafeResourceUrlSafeScriptSafeStyleFor now it seems like the best workaround to access the actual string is to re-sanitize the Safe* value, just like @Muthu points it out in his accepted answer.
Alternatively one can either use any type or force the return value to be a string by using as string after calling the function. Note that this only works for certain scenarios, e.g. assigning HTML code from SafeHtml.
let html: any = this.sanitizer.bypassSecurityTrustHtml("<h1>just some html!</h1>");
let html2: string = this.sanitizer.bypassSecurityTrustHtml("<h1>even more html!</h1>") as string;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With