angular - 在 Angular/Karma/Jasmine 中测试 iframe 返回跨站点脚本错误
问题描述
我有一个带有 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,
},
},
...
解决方案
它似乎工作得很好,使用包含所需所有内容的模块以不同方式导入它。
注意:工作示例。
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();
});
});
推荐阅读
- sql - 全文目录搜索不返回任何结果
- python - ImportError:没有名为 seaborn 的模块(使用交互模式)
- python - 随机离散形状
- javascript - VS 代码对象休息/扩展运算符错误
- angular - AWS 认知 | 如何验证用户是否经过身份验证且有效?
- node.js - 如何在阻止任何公共流量的公司防火墙后面安装 node-oracledb?
- r - R:如何检查列表中是否存在多个列的值
- excel - Excel 公式 - 类似于 IF/THEN 计数 IF
- python - 在 anaconda 中安装 keras 时出错。/p KERAS_BACKEND= 0
我在 anaconda 中创建了一个新环境,在安装了 spyder、tensorflow 和 theano 之后,我尝试安装 keras,但收到一条错误消息(见下文)。现在我什至无法打开 spyder,因为它停止工作。Spyder 仅在我再次卸载 keras 时才有效。
你知道会发生什么吗?我在同一台计算机上有另一个环境,它可以与安
- android - 无论视图被拖动到哪里,都可以在画布上绘制