JavaScript中window.opener与parent的区别详解
本文详细解析JavaScript中window.opener与window.parent的区别。opener用于window.open弹出的子窗口反向引用父窗口,而parent用于iframe或frame嵌入的页面引用父级窗口。文章通过HTML示例代码展示了如何安全使用opener访问父页面DOM,并强调了在使用前进行null判断以避免JS错误的重要性。
window.opener与parent的基本概念
window.opener属性代表“谁打开了当前窗口”。例如,若A页面通过window.open方法打开了B页面,则A页面所在的窗口即为B页面的opener。在B页面中,可以通过opener对象来访问A页面。
window.parent属性表示父窗口。例如,若A页面通过iframe或frame嵌入了B页面,则A页面所在的窗口即为B页面的parent。在JavaScript中,window.opener仅是对弹出窗口的母窗口的一个引用。例如:在a.html中,通过点击按钮等方式window.open出一个新的窗口b.html。那么在b.html中,就可以通过window.opener(省略写为opener)来引用a.html,包括a.html的document等对象,操作a.html的内容。假如这个引用失败,那么将返回null。所以在调用opener的对象前,要先判断对象是否为null,否则会出现“对象为空或者不存在”的JS错误。
window.opener使用示例
示例:aa.html
代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<body>
<span id="name"></span>
<input type="button" " value="弹窗" onclick="window.open('bb.html')" />
</body>
</htmlbb.html
代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<body>
<input type="text" id="inputValue"/>
<input type="button" value="添加" onclick="window.opener.document.getElementById('name').innerHTML=inputValue.value"/>
</body>
</html>window.opener 返回的是创建当前窗口的那个窗口的引用,比如点击了aa.htm上的一个链接而打开了bb.htm,然后我们打算在bb.htm上输入一个值然后赋予aa.htm上的一个id为“name”的textbox中,就可以
写为: window.opener.document.getElementById("name").value = "输入的数据"; window.opener.document.getElementById("name").innerHTML= "输入的数据";
React中怎么不可变地删除JS数组元素
2026-11-05 18:06:01
JS动态构建复杂嵌套JSON对象的方法
2026-11-05 15:41:52
JS负数取余为什么是负数?详解余数与模运算区别
2026-11-05 13:34:41
JS 解压出现乱码或报错怎么解决?
2026-11-05 12:32:38
JS 中 startsWith、indexOf 与正则判断字符串前缀的对比
2026-11-04 22:19:43
