首页 > 解决方案 > 如何读取在 iframe 中打开的网站的网址

问题描述

我正在 Angular 网站上工作,在哪里

我正在通过 iframe 打开另一个网站,

我如何阅读在 iframe 中打开的网站的 url ..?

我把我的代码

.html 文件

<iframe src="https://www.zaubacorp.com/">
  <p>Your browser does not support iframes.</p>
</iframe>

当我搜索如何在 Angular 的 iframe 中读取网站打开的网址时。

我在 javascript 中得到以下建议 如何获取 iframe 的当前位置?

alert(document.getElementById("myiframe").src);
document.getElementById("myiframe").src = 'http://www.google.com/';
alert(document.getElementById("myiframe").documentWindow.location.href);
Error: Permission denied to get property Location.href

但实际上它在 Angular 中不起作用

标签: angulariframe

解决方案


通过 ViewChild,您可以访问 iframe 元素并读取 src。

import { Component, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'hello',
  templateUrl: 'hello.component.html',
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
  @ViewChild('iframe') iframe: ElementRef;

  ngAfterViewInit() {
    console.log(this.iframe.nativeElement.src);
  }
}

您的 HTML:

<iframe #iframe src="https://www.zaubacorp.com/">
  <p>Your browser does not support iframes.</p>
</iframe>

对于演示检查这个这个stackblitz


推荐阅读