首页 > 解决方案 > 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;

这显然不是一个好的解决方案,所以我希望其他人知道如何正确解决这个问题。

标签: angularangular-dom-sanitizer

解决方案


听起来您只想要可以通过调用获得的 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>

推荐阅读