如何从 child iframe 获取 <title> 以在 index.html 上设置

How do I get the <title> from a child iframe to set on the index.html

目前我的 index.html 文件中有以下内容

document.title = document.getElementById('title').contentWindow.document.title;

但它使标题为空,而不是 iframe 的标题。

我该如何解决这个问题?

Here is my site

获取 iframetitle 非常简单:

var iframe = document.getElementById("iframeId");
var iframeTitle = iframe.contentDocument.title;

如果要在加载iframe时获取title的值,执行:

document.getElementById("iframeId").onload = function() {
  var iframeTitle = document.getElementById("iframeId").contentDocument.title;
}

title 值现在存储在您的 iframeTitle 变量中。

之后,您可以用此变量替换当前页面上的标题值。

if (document.title != iframeTitle) {
    document.title = iframeTitle;
}

如果您想将此代码插入 html 文件,请在 <body> 元素中的内容后添加以下代码。

<script>
    document.getElementById("iframeId").onload = function() {
      var iframeTitle = document.getElementById("iframeId").contentDocument.title;
      if (document.title != iframeTitle) {
        document.title = iframeTitle;
      }
    }
</script>