问题描述
我有一个带有 html 和 iframe 的 Angular(10) 组件。
无论我如何清理 URL (bypassSecurityTrustResourceUrl
),我都会收到跨站点脚本错误:
错误:资源 URL 上下文中使用的值不安全(请参阅 http://g.co/ng/security#xss)
以下是我的代码的重要部分。
除了下面的代码,我还尝试硬编码空字符串、有效的 html、null、# 和诸如此类的东西。
我曾尝试操纵我嘲笑的 DomSanitizer;包括关闭它。
我已验证我的模拟已被调用。
现在我猜是 Karma 使用了 iframe,然后我的代码使用了另一个/内部 iframe,而 karma 的设置在我的 iframe 中不允许任何东西。
(让 Angular 不抱怨 iframe src/URL 的 xss 的唯一方法是在模板中对其进行硬编码。)
模板:
<iframe id="inlineFrameExample" [src]="embeddedLink">
</iframe>
.ts:
private url: string // Set elsewhere.
constructor(
private sanitizer: DomSanitizer,) { }
public get embeddedLink(): SafeResourceUrl {
return this.sanitizer.bypassSecurityTrustResourceUrl(this.url);
}
.ts.spec:
...
providers: [
{
provide: DomSanitizer,useValue: {
bypassSecurityTrustResourceUrl: (val: string) => val,},...
解决方法
它似乎工作得很好,使用包含所需一切的模块以不同的方式导入它。
注意:工作 example。
app.module.ts
import { NgModule } from "@angular/core";
import { AppComponent } from "./app.component";
@NgModule({
imports: [],declarations: [AppComponent],bootstrap: [AppComponent]
})
export class AppModule {}
app.component.ts
import { Component } from "@angular/core";
import { DomSanitizer,SafeResourceUrl } from "@angular/platform-browser";
@Component({
selector: "myapp",templateUrl: "app.component.html",styleUrls: ["./app.component.css"]
})
export class AppComponent {
private url: string = "https://www.testUrl.com/";
constructor(public sanitizer: DomSanitizer) {}
public get embeddedLink(): SafeResourceUrl {
return this.sanitizer.bypassSecurityTrustResourceUrl(this.url);
}
}
app.component.spec.ts
import { AppComponent } from "./app.component";
import { ComponentFixture,TestBed } from "@angular/core/testing";
import { AppModule } from "./app.module";
describe("iFrame tests",() => {
let comp: AppComponent;
let fixture: ComponentFixture<AppComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [AppModule],providers: [],declarations: []
});
fixture = TestBed.createComponent(AppComponent);
comp = fixture.componentInstance;
fixture.detectChanges();
});
it("should exist",() => {
expect(comp).toBeTruthy();
});
});