简体   繁体   English

Angular bypassSecurityTrustResourceUrl 未按预期工作

[英]Angular bypassSecurityTrustResourceUrl not working as expected

I'm having a problem where DomSanitizer.bypassSecurityTrustResourceUrl is not working as expected.我遇到了 DomSanitizer.bypassSecurityTrustResourceUrl 没有按预期工作的问题。

I have created the following pipe as found in many sources online:我已经创建了以下 pipe ,在许多在线资源中都可以找到:

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;
  }
} 

This should create a SafeResourceUrl which has a property 'changingThisBreaksApplicationSecurity' which holds a string.这应该创建一个 SafeResourceUrl,它具有一个包含字符串的属性 'changedThisBreaksApplicationSecurity'。 However in my case that property contains an object with an url property which holds the string.但是在我的情况下,该属性包含一个 object 和一个包含字符串的 url 属性。

Expected result: {"changingThisBreaksApplicationSecurity": "whatever the value of url is"}预期结果: {"changingThisBreaksApplicationSecurity": "whatever the value of url is"}

My result: {"changingThisBreaksApplicationSecurity": { "url": "whatever the value of url is" }}我的结果: {"changingThisBreaksApplicationSecurity": { "url": "whatever the value of url is" }}

Because of this it doesn't work when setting it as the src of an iframe, so as a workaround I'm currently overwriting the value因此,将其设置为 iframe 的 src 时它不起作用,因此作为一种解决方法,我目前正在覆盖该值

safeResource["changingThisBreaksApplicationSecurity"] = safeResource["changingThisBreaksApplicationSecurity"].url;

which obviously isn't a nice solution so I was hoping that someone else knows how to properly fix this.这显然不是一个好的解决方案,所以我希望其他人知道如何正确解决这个问题。

It sounds like you just want the resourceUrl which you could get by calling:听起来您只想要可以通过调用获得的 resourceUrl:

URL.createObjectURL(objectToCreateUrlFor);

This would give you the URL of the object.这将为您提供 object 的 URL。 If you want to display the content in the UI, that's when you would use your safepipe to resolve a property to bind to in the UI.如果您想在 UI 中显示内容,那么您将使用安全管道来解析要在 UI 中绑定的属性。 Note: The property you bind to needs to be of a SafeUrl type注意:您绑定的属性需要是 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM