首页 > 解决方案 > 如何在我的 Angular 组件中打开其他网站

问题描述

我正在尝试制作一个应该在组件内打开网站的 Web 应用程序,然后该工具将像 selenium 一样工作。像这样的senerio。用户输入链接并回车。然后我们打开组件里面的网页。有几种方法可以在其中打开网页,如 iframe、嵌入、对象等。但这是网页阻止我的事情,因为CORS POLICY 有没有办法实现这一点。谢谢你。

标签: javascripthtmlcssangulartypescript

解决方案


您需要使用 dom sanitizer,并且您的跨域应该通过 iframe 接受您的请求。

这是一个示例堆栈闪电战。https://stackblitz.com/edit/angular-158g4a

import { Component } from '@angular/core';
import {DomSanitizer} from '@angular/platform-browser';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  constructor(private domSanitizer: DomSanitizer){}
  //https://www.google.com/  // does not work
  //https://angular.io/     // works fine
  url = this.domSanitizer.bypassSecurityTrustResourceUrl('https://angular.io/')
  name = 'Angular';
}

推荐阅读