【问题标题】:how can I read the url to website opening in iframe如何读取在 iframe 中打开的网站的网址
【发布时间】:2019-02-21 14:29:17
【问题描述】:

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

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

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

我正在输入我的代码

.html 文件

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

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

我在 javascript 中得到以下建议 How do I get the current location of an 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 中不起作用

【问题讨论】:

  • 您想要src 的值还是documentWindow.location.href 的值?只有当 iframe 的网站与您的 Angular 网站属于同一来源(域)时,后一种才是可能的。 (正如您链接问题的最佳答案中所述)

标签: angular iframe


【解决方案1】:

您可以通过 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>

如需演示,请查看this stackblitz

【讨论】:

    【解决方案2】:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 2021-12-28
    • 2014-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多