忍者ブログ

29Apr

[PR]

Posted by in

×

[PR]上記の広告は3ヶ月以上新規記事投稿のないブログに表示されています。新しい記事を書く事で広告が消えます。

07May

postMesasge(外部サイトとの連携)

Posted by No Name Ninja in Javascript Sample

マッシュアップの手法でXML,JASONなどの手法がありますが、javascriptのpostMessageを使う手法もあります。
SAMPLE・親HTML

<html>
<head>
<meta http-equiv="Content-Language" content="ja" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>【Javascirpt講座】</title>
<script>


window.onload = function(){
  document.getElementById('button1').onclick = sendMessage;
  window.onmessage = receive;
}

function sendMessage(){
  try{
    var farAwayWindow = document.getElementById('widgetId').contentWindow;
    farAwayWindow.postMessage('Hello PostMessage','*');
  }catch(e){
    alert(e.message);
  }
}

function receive(e){
  alert(e.data + ' from ' + e.origin);
}

</script>
</head>
<body>

<div><button id="button1">PostMessage</button></div>
<iframe src="test.html" id="widgetId" height="200px" scrolling="no" ></iframe>

</body>
</html>

1.送信する場合、対象のwindowオブジェクトを取得し、postMessageを実行するだけです。
第二引数は、'*'もしくは、URIを指定します。
windowオブジェクトが対象URIではない場合、無視されます。


2.メッセージを受信する際に設定します。
e.data・・・・送られてきたデータ
e.origin・・・・送信元のURI


・子フレーム

<html>
<head>
<meta http-equiv="Content-Language" content="ja" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Listener</title>
<script>

window.onload = function(){
  window.onmessage = receive;

}

function receive(e){
  document.getElementById('interruptDiv').innerHTML = e.data + ' from ' + e.origin;
  //メッセージを送り返す
  e.source.postMessage('返信' , '*');
}


</script>
</head>
<body>
<div id="interruptDiv"></div>
<br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/>
</body>
</html>

受信して、送信元に返信をしてしています。
e.sourceで送信元のwindowオブジェクトが取得できるので便利です。
PR

Comment


Vodafone絵文字 i-mode絵文字 Ezweb絵文字