目次 †
内容 †
注意点 †
iframe間の通信 †
参考 †
概要 †
- 異なるドメインから配信されたiframeコンテンツと通信する方法
- HTML5以上ならwindow.postMessageが利用できるが、IE7以下のブラウザに対応しない
- 結局、iframeのURLのアンカー(location.hash)を介して通信するのがベター
- IE7以下ではonhashchangeが使えないので、どっちもどっちなのだが・・・。
- 配列やオブジェクト(連想配列)を渡すときはJSON関数を利用する
- IE8以上ならネイティブで動くが、そうでない場合を考慮してjson2.jsをロードしておく
処理の流れ †
- 親ページ
- json2.jsをロードしておく
<script type="text/javascript" src="/path/to/json2.js"></script>
- iframeを配置(静的もしくはJavaScriptで動的に生成)
<iframe src="http://other-domain.com/a.html"></script>
- iframeコンテンツに配列の値を渡す
var array_to_path = [ "aaa", "bbb" ];
var iframe_obj = document.getElementById( "iframe_id" );
iframe_obj = contentWindow.location.replace( "http://other-domain.com/a.html#" + JSON.stringify( array_to_path ) );
- 子ページ
- location.hashが変わったらコマンドを実行
<meta http-equiv="X-UA-Compatible" content="IE=8" >
<script type="text/javascript">
function do_something(){
var array_from_parent = JSON.parse( location.hash.substring(1) );
if ( array_from_parent instanceof Array ){
// 処理を実行
}
}
// onloadでhash更新を監視
if( typeof( window.onhashchange ) === "object" ){
window.onhashchange = function(){
do_something();
}
} else {
var hash = location.hash;
setInterval(function(){
if ( location.hash != hash ){
do_something();
hash = location.hash;
}
}, 100);
}
</script>
|