在JavaScript中,子窗口可以通过window.opener
属性访问其父窗口。如果子窗口是由父窗口打开的,那么window.opener
将指向父窗口,从而允许子窗口调用父窗口的方法。
window.opener
:一个指向打开当前窗口的那个窗口的引用。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Parent Window</title>
<script>
function openChildWindow() {
var childWindow = window.open('child.html', 'childWindow', 'width=300,height=200');
}
function parentMethod(message) {
alert('Message from child: ' + message);
}
</script>
</head>
<body>
<button onclick="openChildWindow()">Open Child Window</button>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Child Window</title>
<script>
function callParentMethod() {
if (window.opener && !window.opener.closed) {
window.opener.parentMethod('Hello from child!');
}
}
</script>
</head>
<body>
<button onclick="callParentMethod()">Call Parent Method</button>
</body>
</html>
原因:
解决方法:
window.open
打开的。window.opener
的支持可能有所不同,应进行充分测试。通过上述方法,可以实现子窗口与父窗口之间的有效通信。
领取专属 10元无门槛券
手把手带您无忧上云