window.open之postMessage传参数

时间:2023-03-09 15:05:48
window.open之postMessage传参数

这次要实现一个window.open打开子视窗的同时传参数到子视窗,关闭的时候返回参数。

当然简单的做法非常简单,直接在window.open的URL之后接参数即可,但是毕竟get method的参数长度受浏览器的限制,一般从2KB到8KB。

除了get之外,还可以用window.postMessage(), 参考下面的case演示。

主视窗HTML如下:

 <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="js/jquery-3.1.1.min.js" type="text/javascript"></script>
<script type="text/javascript"> function openWin() {
var params = new Array();
params[0] = new Array("CL1", "milo test");
params[1] = new Array("CL2", "Taipei"); var popupwin = window.open("popup.jsp", "Map", "status=0,title=0,height=600,width=800,scrollbars=1");
//onload只能执行一次,也就是如果子窗口有onload事件,可能会覆盖。
popupwin.onload = function(e){
popupwin.postMessage(params, "http://"+window.location.host);
}
popupwin.onunload = function(e){
var val = popupwin.returnValue;
alert(val);
}
} </script>
</head>
<body>
<input type="button" value="Open Window" onclick="openWin()" />
</body>
</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>

运行结果:

window.open之postMessage传参数