2017-08-05 13 views
1

test.htmlという名前のHTMLファイルがあり、そのファイルの内容は次のとおりです。JavaScriptを使用してiframeコンテンツを取得する

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

は今、私はインラインフレームで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> 

事前

+0

それは動作しません 'iframe.contentWindow.document.body.innerHTML' – abagshaw

+0

を使用してみてください。 私も試しました 'iframe.contentDocument.getElementsByTagName( 'body')[0] .innerHTML; iframe.contentDocument.getElementsByTagName( 'html')[0] innerHTML; ' –

+0

'iframe_content'は未定義ですか? – abagshaw

答えて

0

に感謝のコメントで述べたように、あなたはロードする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>

関連する問題