document.getElementsByTagName 在 iframe 中不起作用?
document.getElementsByTagName doesn't work inside an iframe?
我有一个包含 iframe 的简单 html 文档。在这个 iframe 中有一个维基百科页面。现在,我只是想获取维基百科页面的标题并将其输出到日志控制台。
这是我正在使用的代码:
<!DOCTYPE html>
<html>
<head> <!-- Tout ce qui est pas dans le contenu -->
<title> example</title>
</head>
<body>
<h1>A Web Page</h1>
<script>
const iframe = document.createElement("iframe");
iframe.src = "https://en.wikipedia.org/wiki/Mathematics";
iframe.height = 800;
iframe.width = 900;
document.body.appendChild(iframe);
var elmnt = iframe.contentWindow.document.getElementsByTagName("H1");
console.log("the title is " + elmnt[0]);
</script>
</body>
</html>
我希望从此示例的控制台中得到“标题是数学”,但我得到的是“标题未定义”。我查了一下,“数学”确实在维基百科的 h1 标签内,所以我不明白这里的问题。
这是时间问题。
您没有等待文档加载,因此 HTML 尚未解析,元素尚不存在。
iframe.addEventListener("load", () => {
var elmnt = iframe.contentWindow.document.getElementsByTagName("H1");
console.log("the title is " + elmnt[0]);
})
… 解决了那个问题,你立即 运行 变成了 the cross-origin security limits。
我有一个包含 iframe 的简单 html 文档。在这个 iframe 中有一个维基百科页面。现在,我只是想获取维基百科页面的标题并将其输出到日志控制台。 这是我正在使用的代码:
<!DOCTYPE html>
<html>
<head> <!-- Tout ce qui est pas dans le contenu -->
<title> example</title>
</head>
<body>
<h1>A Web Page</h1>
<script>
const iframe = document.createElement("iframe");
iframe.src = "https://en.wikipedia.org/wiki/Mathematics";
iframe.height = 800;
iframe.width = 900;
document.body.appendChild(iframe);
var elmnt = iframe.contentWindow.document.getElementsByTagName("H1");
console.log("the title is " + elmnt[0]);
</script>
</body>
</html>
我希望从此示例的控制台中得到“标题是数学”,但我得到的是“标题未定义”。我查了一下,“数学”确实在维基百科的 h1 标签内,所以我不明白这里的问题。
这是时间问题。
您没有等待文档加载,因此 HTML 尚未解析,元素尚不存在。
iframe.addEventListener("load", () => {
var elmnt = iframe.contentWindow.document.getElementsByTagName("H1");
console.log("the title is " + elmnt[0]);
})
… 解决了那个问题,你立即 运行 变成了 the cross-origin security limits。