2014/4/16

[JavaScript] Iframe Communication

最近遇到了要跟 IFrame 去做互動
使用JavaScript可以達成這樣的需求



首先來製作Parent.htm

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Parent Frame</title>
    <style type="text/css">
        #PT1
        {
            width: 129px;
        }
        #PT2
        {
            width: 168px;
        }
    </style>
</head>
<body>
    <div>
        Send to Child:
        <br />
        <input type="text" id="PT1" size="20" />
        <input type="button" value="Send" onclick="SendMsgToChild()" />
        <br />
        <br />
        Receive From Child:
        <br />
        <input type="text" id="PT2" size="20" /><br />
        <br />
        <hr />
        <iframe src="Child.htm" id="Childframe" width="250px" height="180px"></iframe>
    </div>
</body>
</html>
<script type="text/javascript">
    function SendMsgToChild() {
        document.getElementById('Childframe').contentWindow.ReceiveMsgFromParent(document.getElementById('PT1').value);
    }

    function ReceiveMsgFromChild(message) {
        document.getElementById('PT2').value = message;
    }
</script>


看到裡面有一個<IFrame>的控制項,這邊決定子視窗的路徑
id="Childframe"很重要,要給他id,之後才能找到他

按鈕的觸發事件就會傳送訊息給Child.htm,會去呼叫他的ReceiveMsgFromParent()
document.getElementById('Childframe').contentWindow.ReceiveMsgFromParent(document.getElementById('PT1').value);

ReceiveMsgFromChild()是接收來自Child.htm的訊息


接著來看 Child.htm
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Child Frame</title>
    <style type="text/css">
        #CT2
        {
            width: 129px;
        }
        #CT1
        {
            width: 168px;
        }
    </style>
</head>
<body>
    <div>
        Receive From Parent:
        <br />
        <input type="text" id="CT1" size="20" /><br />
        <br />
        Send to Parent:
        <br />
        <input type="text" id="CT2" size="20" />
        <input type="button" value="Send" onclick="SendMsgToParent()" />
        <br />
    </div>
</body>
</html>
<script type="text/javascript">
    function SendMsgToParent() {
        parent.ReceiveMsgFromChild(document.getElementById('CT2').value);
    }

    function ReceiveMsgFromParent(message) {
        document.getElementById('CT1').value = message;
    }
</script>


這邊可以看到ReceiveMsgFromParent(),這個就是給Parent呼叫的

按鈕的觸發事件會去呼叫"Parent"的Function
這邊的Parent是關鍵字,會直接導向呼叫這IFrame的那一頁
不用知道父視窗的id
 parent.ReceiveMsgFromChild(document.getElementById('CT2').value);

假設有多層的IFrame呼叫"祖父"的那一頁
只要這樣寫
parent.parent.ReceiveMsgFromChild(document.getElementById('CT2').value);


Demo: