【JQuery】iframeの高さを動的に取得する方法(クロスドメイン対応) その1
iframeの高さを読み込んだページ(別ドメインのページ)の高さに動的に変更する方法をご紹介。
例)
親ページ → https://parent.co.jp/parent.html
子ページ → https://child.co.jp/child.html
parent.html
<head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <script type="text/javascript"> window.addEventListener("message", receiveSize, false); function receiveSize(e) { if (e.origin === "https://child.co.jp") document.getElementById("childIFrame").style.height = e.data + "px"; } </script> </head> <body> <iframe src="https://child.co.jp/child.html" frameborder="0" scrolling="no">この部分は iframe 対応のブラウザでご覧ください。</iframe> </body>
child.html
<head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <script type="text/javascript"> window.addEventListener("load", postSize, false); function postSize(e){ var target = parent.postMessage ? parent : (parent.document.postMessage ? parent.document : undefined); if (typeof target != "undefined" && document.body.scrollHeight) target.postMessage(document.getElementById("foo").scrollHeight, "*"); } </script> </head> <body id="foo"> ・・・ </body>
※iframeが複数ある場合だと上記方法ではうまくいかないので、iframeが1つの場合のみご使用ください。
コメントを残す