JS一千问(5):window次窗口如何访问主窗口?

JavaScript打开新窗口,以及传递数据,主窗口访问次窗口十分便捷。

window.open返回次窗口的Window对象,可以挂载所需数据。

// main.html 主窗口

var handle = window.open('child.html');
handle.data = "hello world";

反过来,次窗口访问主窗口,需要用到window.opener属性。比如,次窗口修改主窗口的背景颜色,用window.opener.document.bgColor。

<button onClick="window.opener.document.bgColor='yellow'">Yellow</button> 

不仅如此,还可以用window.opener.location重定向主窗口。

window.opener.location = 'http://xxx';

完整代码:

// child.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>二级窗口</title>
</head>
<body>
<button onClick="changeColor()">改变主窗口背景颜色</button> 
<button onClick="locationMain()">重定向主窗口</button> 

<script type="text/javascript">

	// 接收主窗口数据
	alert(window.data);

	function changeColor() {
		window.opener.document.bgColor='yellow'; 
	}

	function locationMain() {
		window.opener.location = 'https://ai.pkoala.com';
	}
</script>
</body>
</html>

Leave a Comment

您的电子邮箱地址不会被公开。 必填项已用*标注