Home > しらべる > iFrameを使ったクロスドメイン通信

iFrameを使ったクロスドメイン通信

  • Posted by: memorycraft
  • 2010年3月25日 21:24
  • しらべる

HTMLでJSを使用したクロスドメインのやりとりにはいくつか方法がありますが、
サーバーサイドを介さない方法として、iFrame内iFrameの方法を紹介します。
通常、別ドメインのiFrameには親ページからアクセスできませんが、
iFrame内に親ページと同じドメインのiFrameを配置することにより別ドメインの子から親ページへパラメータを渡すことができます。

構成は以下の通り

親のページ(http://www.memorycraft.jp/parent.html)

<html>
<head>
<title>parent</title>
<script type="text/javascript">
<!--
function change(param){
	document.getElementById("note").innerHTML = param;
	frames[0].frames[0].location.href = 'dummy.gif';
}
//-->
</script>
</head>
<body>
<div>test <span id="note"></span></div>
<iframe id="ifr" src="http://www.example.com/child.html" style="border" width="100" height="100" scrolling="no">
</iframe>
</body>
</html>

子のiFrame内のページ(http://www.example.com/child.html)

<html>
<head>
<title>child</title>
</head>
<body>
<a href="javascript:document.getElementById('iifr').setAttribute('src','http://www.memorycraft.jp/grandchild.html#hoge');">A</a>
<a href="javascript:document.getElementById('iifr').setAttribute('src','http://www.memorycraft.jp/grandchild.html#moge');">B</a>
<iframe id="iifr" name="iifr" src="dummy.gif"></iframe>
</body>
</html>

孫のiFrame内のページ(http://www.memorycraft.jp/grandchild.html)

<html>
<head>
<title>inner</title>
<script language="javascript">
<!--
window.onload = function check(){
	if(location.hash != null && location.hash != '' && location.hash != undefined){
		window.top.change(location.hash);
	}
}
//-->
</script>
</head>
<body>
dummy
</body>
</html>

処理の流れ


  1. 孫のiFrameのソースURLには予めダミー用のURLをセットしておく

  2. 子のiFrame内のリンク押下に応じて、孫のiFrameのソースURLを指定する。その際、親に渡したいパラメータをアンカーリンク(#以降)として指定する。

  3. 孫のページがロードされたら、onloadにより、自分のlocation.hashをパラメータとして、window.topの関数の引数として渡す。孫から親は同一ドメインなので関数呼び出しができる。

  4. 親は呼び出された関数内でパラメータを受け取り、任意の処理を行う。

以上で子のiFrameから親ページにパラメータを渡すことができます。
ただし、この方法は孫ページの遷移時にIEだとクリック音がなるので注意です。

関連記事

Trackbacks:0

TrackBack URL for this entry
http://www.memorycraft.jp/mt-tb.cgi/111
Listed below are links to weblogs that reference
iFrameを使ったクロスドメイン通信 from メモリークラフト

Comments:0

Comment Form

Home > しらべる > iFrameを使ったクロスドメイン通信

ページの先頭へ戻る