自分で作ったり提供したりするものは、まず自分自身で使ってみろろということです。自分じゃ使わないものなら人はいくらでも無責任にも無思考にもなれる。そういう投げやりな「サービス」やら「プロダクツ」なんて、だれだってイヤだ。自分が作り手と同時に利用者の立場になれば、ちゃんと使えるレベルのものを提供しようとします。

2010年10月6日水曜日

html5 Communication APIsを通じてドキュメント間の通信機能を実現

 この前はウェブページ間のデータ交換などの処理はほとんどURLパラメータや、openerなどの方式で実装されるんですが、HTML5から新しい通信APIが提供されました、これはCommunication APIsとなります。

サンプル:
http://html5next.appspot.com/postMessagePortal.html

このサンプルはホストページとIFrameページ間のデータ交換処理を示しています。


postMessagePortal.html ソース:
<script type="text/javascript">
if (typeof window.postMessage === "undefined") { 
    alert("残念ですが、あなたのブラウザーはメッセージAPIをサポートしていません。"); 
}

var notificationTimer = null;

function messageHandler(e) {
    if (e.origin == "http://html5next.appspot.com") {
        notify(e.data);
    } else {
     alert("予想外:" + e);
    }
}
function blinkTitle(m1, m2) {
    document.getElementById("divTitle").innerHTML = m1;
    notificationTimer = setTimeout(blinkTitle, 1000, m2, m1)
}
function notify(message) {
    stopBlinking();
    blinkTitle(message, "");
}
function sendString(s) {
    document.getElementById("widget").contentWindow.postMessage(s, "http://html5next.appspot.com");
}
function sendStatus() {
    var statusText = document.getElementById("statusText").value;
    sendString(statusText);
}
function stopBlinking() {
    if (notificationTimer !== null) {
        clearTimeout(notificationTimer);
    }
    document.getElementById("divTitle").innerHTML = "";
}
function loadDemo() {
    document.getElementById("sendButton").addEventListener("click", sendStatus, true);
    document.getElementById("stopButton").addEventListener("click", stopBlinking, true);
    sendStatus();
}
window.addEventListener("load", loadDemo, true);
window.addEventListener("message", messageHandler, true);
</script>
postMessageWidget.html ソース:
<script type="text/javascript">
function messageHandler(e) 
{
    if (e.origin === "http://html5next.appspot.com") 
    {
        document.getElementById("status").textContent = e.data;
    } else 
    {
        alert("予想外:" + e);
    }
}
function sendString(s) 
{
    window.top.postMessage(s, "http://html5next.appspot.com");
}
function loadDemo() {
    document.getElementById("actionButton").addEventListener("click",
        function() {
            var messageText = document.getElementById("messageText").value;
            sendString(messageText);
        }, true);
}
window.addEventListener("load", loadDemo, true);
window.addEventListener("message", messageHandler, true);
</script>

0 件のコメント:

コメントを投稿

ホームページ