在JavaScript中,子窗口可以通过window.opener
属性访问其父窗口。如果子窗口是通过window.open()
方法打开的,那么window.opener
将指向打开它的窗口。这样,子窗口就可以调用父窗口中定义的方法。
window.opener
: 这是一个指向打开当前窗口的那个窗口的引用。postMessage
方法可以在不同源的窗口之间安全地传递消息。window.opener.methodName()
调用父窗口的方法。postMessage
进行跨窗口通信,适用于不同源的情况。<!DOCTYPE html>
<html>
<head>
<title>Parent Window</title>
</head>
<body>
<button onclick="openChildWindow()">Open Child Window</button>
<script>
function openChildWindow() {
window.childWindow = window.open('child.html', 'childWindow');
}
function parentMethod() {
alert('This method is called from the child window!');
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Child Window</title>
</head>
<body>
<button onclick="callParentMethod()">Call Parent Method</button>
<script>
function callParentMethod() {
if (window.opener && !window.opener.closed) {
window.opener.parentMethod();
} else {
alert('Parent window is not available.');
}
}
</script>
</body>
</html>
原因:
解决方法:
postMessage
进行安全通信。postMessage
进行跨域通信父窗口代码:
window.addEventListener('message', function(event) {
if (event.origin !== 'http://example.com') return; // 安全检查
if (event.data === 'callParentMethod') {
parentMethod();
}
});
子窗口代码:
function callParentMethod() {
window.opener.postMessage('callParentMethod', 'http://example.com');
}
通过这种方式,即使子窗口和父窗口不在同一个域,也可以安全地进行通信。
领取专属 10元无门槛券
手把手带您无忧上云