假設有兩個網頁:aaa.jsp和bbb.jsp,然後從AAA.jsp傳輸資料到BBB.jsp內。
--------------------------------------------------------------------------------------------------------
aaa.jsp的內容:
<%@ page language="java" contentType="text/html; charset=BIG5" pageEncoding="BIG5"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=BIG5"> <title>AAA</title> </head> <script type="text/javascript"> function sendMessage() { var menu = document.getElementById( "bbbID" ).contentWindow; menu.postMessage( document.getElementById( "messageID" ).value, 'http://localhost:8080' ); } </script> <body> <iframe src = "bbb.jsp" id = "bbbID" frameborder = "1" scrolling = "auto"></iframe> <form> <input type = "text" id = "messageID" value = ""> <input type = "button" value = "傳送訊息給bbb" onclick = "sendMessage()"> </form> </body> </html>
--------------------------------------------------------------------------------------------------------
bbb.jsp的內容:
<%@ page language="java" contentType="text/html; charset=BIG5" pageEncoding="BIG5"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=BIG5"> <title>Insert title here</title> </head> <script type="text/javascript"> function getMessage( event ) { if( event.origin != 'http://localhost:8080' ) { alert( event.origin ); return; } document.getElementById( "receiveID" ).innerHTML = event.data; } if( typeof window.addEventListener != 'undefined' ) { window.addEventListener( 'message', getMessage, false ); } else if( typeof window.attachEvent != 'undefined' ) { window.attachEvent( 'onmessage', getMessage ); } </script> <body> <h1>這是bbb!</h1> <div id = "receiveID">等待接收訊息!</div> </body> </html>
--------------------------------------------------------------------------------------------------------
aaa.jsp內的postMessage有兩個參數,前面是要夾帶的資料,後面是傳送的網域;然後在bbb.jsp內可以用event.origin來判斷網域是否相符,是個保險機制。如果不需要這層保險機制,可以將後面的參數設為'*',這樣接收端也可以不用進行檢查。
例如在aaa.jsp內將
menu.postMessage( document.getElementById( "messageID" ).value, 'http://localhost:8080' );
改為
menu.postMessage( document.getElementById( "messageID" ).value, '*' );
然後在bbb.jsp內將
function getMessage( event ) { if( event.origin != 'http://localhost:8080' ) { alert( event.origin ); return; } document.getElementById( "receiveID" ).innerHTML = event.data; }
改為
function getMessage( event ) { document.getElementById( "receiveID" ).innerHTML = event.data; }
--------------------------------------------------------------------------------------------------------
而之所以會同時使用addEventListener和attachEvent,是因為以前各大瀏覽器不一定會支援addEventListener,現在如何我是不知道啦......因此先檢查addEventListener能不能用,不行再用attachEvent。
網路上可找到許多關於addEventListener和attachEvent的詳細解釋,不需要我這個外行人做粗淺的說明了。
沒有留言:
張貼留言