简体   繁体   English

如何在 angular 中嵌入外部 url?

[英]How to embed external urls in angular?

I'm trying to embed an external url inside my angular app using iframe.我正在尝试使用 iframe 在我的 angular 应用程序中嵌入外部 url。 This is what I'm getting.这就是我得到的。

如何以角度嵌入外部网址?

and the error says that:错误说:

在此处输入图像描述

Following is the template in which I'm trying to embed an external url以下是我尝试在其中嵌入外部 url 的模板

<iframe height="500" width="100%" [src]="url | safe" frameborder="0"></iframe>

//   url = `https://fonts.google.com/`;

// this is a dummy url. this url will be replaced by a page on my another website (owned by myself but different domain)

Following is the pipe used to bypass security risk:以下是用于绕过安全风险的 pipe:

@Pipe({
  name: 'safe',
})
export class SafePipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {}
  transform(url): SafeResourceUrl {
    return this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }
}

And still I'm getting the following error & the external webpage is not getting embedded.而且我仍然收到以下错误并且外部网页没有被嵌入。

Refused to display 'https://fonts.google.com/' in a frame because it set 'X-Frame-Options' to 'sameorigin'.

Note I'm using latest version of angular注意我使用的是最新版本的 angular

The above method is something I found online.上面的方法是我在网上找到的。 I couldn't find anything else.我找不到其他任何东西。 Can someone suggest a best approach to embed external urls as an iframe .有人可以建议将外部网址嵌入为iframe的最佳方法。

This error means that the site you are trying to embed, https://fonts.google.com/ , doesn't allow sites with a different domain name to embed it.此错误表示您尝试嵌入的站点https://fonts.google.com/不允许具有不同域名的站点嵌入它。 There is no way to bypass, you can read more about this on mdn没有办法绕过,你可以在mdn上阅读更多相关信息

if you specify SAMEORIGIN, you can still use the page in a frame as long as the site including it in a frame is the same as the one serving the page.如果您指定 SAMEORIGIN,您仍然可以在框架中使用该页面,只要将其包含在框架中的站点与提供该页面的站点相同。

You can try the JSONP approach to avoid the CORS issues:您可以尝试JSONP 方法来避免 CORS 问题:

HTML: HTML:

<iframe #iframe type="text/javascript" frameborder="0" scrolling="no"></iframe>

TS: TS:

src: string; // <- YOUR URL
@ViewChild('iframe') iframe: ElementRef;

 ngAfterViewInit() {
   const doc = this.iframe.nativeElement.contentDocument || this.iframe.nativeElement.contentElement.contentWindow;
   const content = `
       <html>
       <head>
         <base target="_parent">
       </head>
       <body>
       <script type="text/javascript" src="${this.src}"></script>
       </body>
     </html>
   `;

   doc.open();
   doc.write(content);
   doc.close();
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM