window.open之postMessage傳參數

此次要實現一個window.open打開子視窗的同時傳參數到子視窗,關閉的時候返回參數。javascript

固然簡單的作法很是簡單,直接在window.open的URL以後接參數便可,可是畢竟get method的參數長度受瀏覽器的限制,通常從2KB到8KB。html

除了get以外,還能夠用window.postMessage(), 參考下面的case演示。java

主視窗HTML以下:jquery

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="UTF-8">
 5 <title>Insert title here</title>
 6 <script src="js/jquery-3.1.1.min.js" type="text/javascript"></script>
 7 <script type="text/javascript">
 8 
 9         function openWin() {
10             var params = new Array();
11             params[0] = new Array("CL1", "milo test");
12             params[1] = new Array("CL2", "Taipei");
13             
14             var popupwin = window.open("popup.jsp", "Map", "status=0,title=0,height=600,width=800,scrollbars=1");
15             //onload只能執行一次,也就是若是子窗口有onload事件,可能會覆蓋。
16             popupwin.onload = function(e){
17                 popupwin.postMessage(params, "http://"+window.location.host);
18             }
19             popupwin.onunload = function(e){
20                 var val = popupwin.returnValue;
21                 alert(val);
22             }
23         }
24 
25     </script>
26 </head>
27 <body>
28 <input type="button" value="Open Window" onclick="openWin()" />
29 </body>
30 </html>

打開子視窗以後,要給視窗傳參數params,並在子視窗上顯示出參數值。瀏覽器

但前提是子視窗必須已經完成監聽事件message的填加,不然onload的時候參數傳過去也收不到。爲了解決這個問題,子視窗必需要在onload事件執行以前添加message事件監聽。這裏我是添加document.onreadystatechange事件,先看看html的document.readyState, 總的有五個取值:安全

  • uninitialized - Has not started loading yet
  • loading - Is loading
  • loaded - Has been loaded
  • interactive - Has loaded enough and the user can interact with it
  • complete - Fully loaded

爲了在onload被fired以前且安全的添加window事件,這裏選擇用complete,DOC所有加載完且還未觸發onload。jsp

子視窗參考以下:post

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>popup window</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script language="javascript" type="text/javascript">
    function closeWin() {
        window.returnValue = true;
        window.close();
    }
    //HTML DOM fully loaded, and fired window.onload later. 
    document.onreadystatechange = function(e)
    {
        if (document.readyState === 'complete')
        {
            window.addEventListener('message', function(e){
                var params = e.data;
                $('#cl1').text(params[0][1]);
                $('#cl2').text(params[1][1]);
            });
        } 
    };
</script>
</head>
<body>
Parameter CL1: <b id="cl1"></b>
Parameter CL2: <b id="cl2"></b>
<div><input type="button" value="Return Value" onclick="closeWin()" /></div>
</body>
</html>

運行結果:ui

相關文章
相關標籤/搜索