window.open之postMessage传参数
这次要实现一个window.open打开子视窗的同时传参数到子视窗,关闭的时候返回参数。
当然简单的做法非常简单,直接在window.open的URL之后接参数即可,但是毕竟get method的参数长度受浏览器的限制,一般从2KB到8KB。
除了get之外,还可以用window.postMessage(), 参考下面的case演示。
主视窗HTML如下:
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。
子视窗参考如下:
<%@ 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>
运行结果: