angular - Angular bypassSecurityTrustResourceUrl 没有按预期工作
问题描述
我遇到了 DomSanitizer.bypassSecurityTrustResourceUrl 没有按预期工作的问题。
我创建了以下管道,可在许多在线资源中找到:
import { DomSanitizer, SafeResourceUrl} from '@angular/platform-browser';
@Pipe({ name: 'safepipe' })
export class SafePipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) {}
transform(url: string): SafeResourceUrl {
var safeResource = this.sanitizer.bypassSecurityTrustResourceUrl(url);
return safeResource;
}
}
这应该创建一个 SafeResourceUrl,它具有一个包含字符串的属性 'changedThisBreaksApplicationSecurity'。但是在我的情况下,该属性包含一个具有 url 属性的对象,该属性包含字符串。
预期结果:
{"changingThisBreaksApplicationSecurity": "whatever the value of url is"}
我的结果:
{"changingThisBreaksApplicationSecurity": { "url": "whatever the value of url is" }}
因此,将其设置为 iframe 的 src 时它不起作用,因此作为一种解决方法,我目前正在覆盖该值
safeResource["changingThisBreaksApplicationSecurity"] = safeResource["changingThisBreaksApplicationSecurity"].url;
这显然不是一个好的解决方案,所以我希望其他人知道如何正确解决这个问题。
解决方案
听起来您只想要可以通过调用获得的 resourceUrl:
URL.createObjectURL(objectToCreateUrlFor);
这将为您提供对象的 URL。如果您想在 UI 中显示内容,那么您将使用安全管道来解析要在 UI 中绑定的属性。注意:您绑定的属性需要是 SafeUrl 类型
// .ts file
public safePipedContent: SafeUrl;
// use your pipe to set the value of safePipedContent
// use property binding to display your content
<iframe [src]="safePipedContent"></iframe>
推荐阅读
- sql - 查找有多个不同值的 SQL 表行
- java - 调用 Retrofit 返回 null
- angular - 如何返回来自响应的数据
- r - 用 ggplot 映射州边界
- python - 来自 Data 的 Pandas DataFrame DDL 语句
- laravel - AWS ElasticSearch Service 上的身份验证最终失败
- git - git status 使用了错误的路径
- python-3.x - 基于大型数据集的文本匹配技术以获取文本匹配 ID
- c++ - 如何将 boost::log::expressions 格式化程序对象插入流以格式化时间戳
- firebase - firebase.User 对象是否包含不应与其他用户共享的敏感数据?