Javascript で iframe の本体のコンテンツを取得するにはどうすればよいでしょうか? 質問する

Javascript で iframe の本体のコンテンツを取得するにはどうすればよいでしょうか? 質問する
<iframe id="id_description_iframe" class="rte-zone" height="200" frameborder="0" title="description">
  <html>
    <head></head>
    <body class="frameBody">
      test<br/>
    </body>
  </html>
</iframe>

私が得たいものは次のとおりです:

test<br/>

ベストアンサー1

正確な質問は、jQuery ではなく純粋な JavaScript でそれを実行する方法です。

しかし、私は常に jQuery のソース コードにあるソリューションを使用します。これは、ネイティブ JavaScript の 1 行だけです。

私にとっては最高で、読みやすく、私の知る限りiframe コンテンツを取得する最も短い方法。

まずiframeを取得します

var iframe = document.getElementById('id_description_iframe');

// or
var iframe = document.querySelector('#id_description_iframe');

そしてjQueryのソリューションを使う

var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;

contentWindowこれは、オブジェクトのプロパティ中にこのトリックを実行する Internet Explorer でも機能しますiframe。他のほとんどのブラウザはcontentDocumentプロパティを使用するため、この OR 条件で最初にこのプロパティを検証します。設定されていない場合は、 を試してくださいcontentWindow.document

iframe内の要素を選択する

次に、通常getElementById()は または を使用してquerySelectorAll()、 から DOM 要素を選択できますiframeDocument

if (!iframeDocument) {
    throw "iframe couldn't be found in DOM.";
}

var iframeContent = iframeDocument.getElementById('frameBody');

// or
var iframeContent = iframeDocument.querySelectorAll('#frameBody');

iframe内で関数を呼び出す

windowから要素のみを取得してiframe、いくつかのグローバル関数、変数、またはライブラリ全体 (例jQuery) を呼び出します。

var iframeWindow = iframe.contentWindow;

// you can even call jQuery or other frameworks
// if it is loaded inside the iframe
iframeContent = iframeWindow.jQuery('#frameBody');

// or
iframeContent = iframeWindow.$('#frameBody');

// or even use any other global variable
iframeWindow.myVar = window.myVar;

// or call a global function
var myVar = iframeWindow.myFunction(param1 /*, ... */);

注記

これらはすべて、同一生成元ポリシー

おすすめ記事