gpt4 book ai didi

javascript - 使用 JavaScript 获取 iframe 内容

转载 作者:行者123 更新时间:2023-11-28 04:20:00 25 4
gpt4 key购买 nike

我有一个名为 test.html 的 HTML 文件,下面是该文件的内容。

<html>
<head></head>
<body>
This is the content.
</body>
</html>

现在我有另一个文件,我想通过 iframe 显示 test.html 内容,然后将内容与某些内容进行匹配,如果匹配则执行某些操作。

这是我正在尝试的,但我没有获取 iframe 数据。

<html>
<head></head>
<body>
<iframe id="myIframe" src="test.html"></iframe>
<script>
var iframe = document.getElementById("myIframe");
var iframe_content = iframe.contentDocument.body.innerHTML;
var content = iframe_content;

// var content = "This is the content."; --> I want to get the iframe data here like this. Then match it with the following.

var find = content.match(/ is /);
if (find) {
document.write("Match Found");
} else {
document.write("No Match!");
}
</script>
</body>
</html>

提前致谢

最佳答案

正如评论中所述,您需要等待iframe内容加载。 https://developer.mozilla.org/en-US/docs/Web/Events/load

<iframe id="myIframe" src="https://stackoverflow.com/questions/45525117/get-iframe-content-by-using-javascript#"></iframe>
<script>
const myFrame = document.getElementById('myIframe');
myFrame.addEventListener('load', (evt) => {
console.log(evt.target === myFrame);
console.log(evt.target);
});
</script>

关于javascript - 使用 JavaScript 获取 iframe 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45525117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com