Reputation: 655
I'm trying to use the Object html tag to display a PDF that i made server side, but when i hard code the url it works and when i put it in a variable it gives me an Angular error and nothing is shown :
unsafe value used in a resource URL context
i tried using the sanitizer first but i read that it should be used only with tags that support href / src
in my case it's data like this :
<object data="{{pdfSrc}}" type="application/pdf" width="100%" height="100%">
</object><br>
Here is what i tried first :
pdfSrc: any =this.sanitizer.bypassSecurityTrustUrl('http://my_url.com') ;
thank you
Upvotes: 6
Views: 29098
Reputation: 13949
I am adding an answer that builds on many comments and existing answers, because I had trouble finding the appropriate way to make things work.
First, I do not understand why most answers to this question use bypassSecurityTrustResourceUrl
(here on SO or when googling), because we definitely don't want to bypass security, we want to sanitize an unsafe input!
Using bypassSecurityTrustResourceUrl
could make sense when the input was previously sanitized, but this should happen always at the last stage, and therefore if you do not know what you're doing, definitely do not bypassSecurity
!
Tested in angular 13
EDIT: code becomes more complex to handle background image urls wrapped in "url(...)". But you can simplify it if you only need either img or background-image
# component.ts
import { DomSanitizer } from '@angular/platform-browser';
export class MyClass {
constructor(private sanitizer: DomSanitizer)
myUrl({ wrapInUrl = false }: { wrapInUrl?: boolean }={}): SafeResourceUrl | false {
if(!this.event.bannerUrl) {
return false;
}
const sanitized = this.sanitizer.sanitize(SecurityContext.URL, this.myUrl);
return wrapInUrl
? `url(${sanitized})`
: sanitized;
}
}
<!-- component.html -->
<img
[src]="myUrl()"
*ngIf="myUrl()"
>
<div [style.background-image]="myUrl({wrapInUrl: true})">
As mentioned in previous answers (please give them credit as well), it is important to have exactly [src]="yourSanitizedValue"
because feeding anything else (like a string interpolation) would remove the SafeResourceUrl type.
Upvotes: 2
Reputation: 7372
The title of your question is "how to sanitize url for angular 4", yet instead of sanitizing you are actually bypassing the safety check. You should probably sanitizeUrl
instead.
Upvotes: 6
Reputation: 657238
You need to use to bind the result of the sanitizer
[data]="pdfSrc"
because
data="{{pdfSrc}}"
is only for string binding which cause sanitization information being stripped
Upvotes: 8
Reputation: 655
i found the solution based on Günter Zöchbauer Answer i used his method but instead of just the variable I passed the function that sanitizes the URl like this :
<object [data]="cleanURL(pdfSrc)" type="application/pdf" width="100%" height="100%">
</object>
and here is CleanURL function :
cleanURL(oldURL ): SafeUrl {
return this.sanitizer.bypassSecurityTrustResourceUrl(oldURL);
}
Upvotes: 2