【问题标题】:Cross domain issue with IFrame in Angular2Angular2中IFrame的跨域问题
【发布时间】:2017-11-27 10:04:49
【问题描述】:

我们打算访问托管在同一台机器上但在不同端口上的另一个应用程序 url。所以我的 Angular 2 应用程序 http://localhost:8081/app/ 正在尝试打开托管在同一服务器上但端口不同的站点,即 localhost:9100

We are trying to access following url in an iframe
url = http://localhost:9100/custom/getCustomPage

<iframe id="customFrame" *ngIf="url !== null" frameborder="0" [src]="url"></iframe>

Chrome/Firefox DOMException 上的错误:阻止了具有原点的框架 “http://localhost:9100”访问跨域框架。 at http://localhost:9100/custom/getCustomPage 其中 Host:localhost:9100 Referer:http://localhost:8081/app/

我在响应过滤器中添加了以下标题:

Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:X-Requested-With, Content-Type
Access-Control-Allow-Methods:GET, POST, DELETE, PUT
Access-Control-Allow-Origin:*
Access-Control-Expose-Headers: content-length, Allow

请帮助我确定一种解决方法,以便 iFrame 允许显示结果。

目前在 IE 11 中运行良好。

【问题讨论】:

    标签: javascript angular iframe


    【解决方案1】:

    您必须使用 Dom sanitizer 将您的 URL 作为受信任的 url 返回以绕过安全性。以下是您可以执行的操作:

    在您的 html 中:

    <iframe [src]='getSourceURL()'></iframe>
    

    ...在你的打字稿中:

    import { DomSanitizer } from '@angular/platform-browser';
    
    @Component({
        ....
    })
    export class YourComponent {      
    
        yourIFrameUrl: string;
        constructor(public sanitizer: DomSanitizer) { }
    
        getSourceURL() {
            return this.sanitizer.bypassSecurityTrustUrl(this.yourIFrameUrl);
        }
    }
    

    【讨论】:

    • 感谢 Faisal,我已使用 DOMSanitizer 绕过安全性。然而,错误发生在响应页面中,无论它试图引用 window.parent 语言环境:window.parent.dojo? window.parent.dojo.locale : 'en'
    • 我无法使用 this.sanitizer.bypassSecurityTrustUrl 使其工作,但 this.sanitizer.bypassSecurityTrustResourceUrl 完成了这项工作。
    猜你喜欢
    • 2012-03-12
    • 2012-12-11
    • 2011-02-18
    相关资源
    最近更新 更多