首页 > 解决方案 > Angular 7 应用程序中的 iframe 跨域问题

问题描述

我们在第三方(供应商)的网站中有我们的自定义标签。我们的自定义选项卡包含项目列表。单击特定项目时,我们需要打开包含该项目详细信息的父网站页面。父应用程序和我们的应用程序都是 Angular 应用程序。

我们使用 iframe 来显示父应用程序页面。但是,由于我们的应用程序域与父应用程序域不同,我们得到了错误DOMException: Blocked a frame with origin "https://ourCustomTab.cloudfront.net" from accessing a cross-origin frame.

我们正在使用frame.contentWindow.location.href= https://parentApp.com/items打开父应用程序页面。请建议我是否可以使用其他替代方法来打开父应用程序页面,例如我们在应用程序中进行路由。如果 iframe 是唯一的解决方案,那么我们如何实现它?

标签: javascriptangulariframe

解决方案


假设您在 iframe 中使用的外部 URL 有问题,您可以使用 domsanitizer 来清理 URL

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer} from '@angular/platform-browser';
 @Pipe({ name: 'sanitize' })
   export class SanitizePipe implements PipeTransform {
     constructor(private domSanitizer: DomSanitizer) {}
      transform(url) {
       return this.domSanitizer.bypassSecurityTrustResourceUrl(url);
      }
    } 

将此管道添加到 HTML 中的 iframe

<iframe width="100" height="100" [src]="url | sanitize"></iframe>

推荐阅读