简体   繁体   English

使用 JavaScript 获取 iframe 内容

[英]Get iframe content by using JavaScript

I have a HTML file named test.html and below are the content of that file.我有一个名为test.html的 HTML 文件,下面是该文件的内容。

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

Now I have another file where I want to show the test.html content by iframe and then match the content with something and do something if it matches.现在我有另一个文件,我想通过 iframe 显示test.html内容,然后将内容与某些内容进行匹配,如果匹配则执行某些操作。

Here is what I'm trying but I'm not getting the iframe data.这是我正在尝试但我没有得到 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>

Thanks in advance提前致谢

As stated in the comments, you need to wait for the iframe content to load.如评论中所述,您需要等待iframe内容加载。 https://developer.mozilla.org/en-US/docs/Web/Events/load 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>

除非您的网页和 iframe 具有相同的来源,否则什么都不会起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM