在Angular/Karma/Jasmine中测试iframe返回跨站点脚本错误



我有一个Angular(10(组件,其中包含带有iframe的html
无论我如何处理URL(bypassSecurityTrustResourceUrl(,我都会收到一个跨站点脚本错误:

错误:在资源URL上下文中使用了不安全的值(请参阅http://g.co/ng/security#xss)

下面是我的代码的重要部分。

除了下面的代码外,我还尝试过对空字符串、有效html、null、#等进行编码
我试着操纵我嘲笑的DomSanitizer;包括关闭它。
我已经验证我的mock被调用了。

现在我想是因果报应使用了一个iframe,然后我的代码使用了另一个/内部iframe——在某些地方因果报应的设置不允许我的iframe中有任何内容。

(我让Angular不抱怨xss-iframe-src/URL的唯一方法是在模板中对其进行硬编码。(


模板:

<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,
},
},
...

它似乎工作得很好,用包含所需一切的模块以不同的方式导入它。

注:工作示例。

应用程序模块.ts

import { NgModule } from "@angular/core";
import { AppComponent } from "./app.component";
@NgModule({
imports: [],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule {}

应用程序组件.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);
}

}

应用程序组件规范

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

最新更新