在Web开发中,弹出窗口(window.open()或通过target="_blank"打开的窗口)与父窗口之间存在一定的通信机制。当需要从弹出窗口调用父窗口的函数时,可以通过window.opener属性来访问父窗口的上下文。
// 在弹出窗口中调用父窗口的jQuery函数
window.opener.$('#parentElement').someFunction();
// 在弹出窗口中
var myVariable = "Hello from popup!";
window.opener.parentFunction(myVariable);
父窗口(parent.html):
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<button id="openPopup">打开弹出窗口</button>
<div id="result"></div>
<script>
// 父窗口中的jQuery函数
function updateParentContent(message) {
$('#result').text('来自弹出窗口的消息: ' + message);
}
$('#openPopup').click(function() {
window.open('popup.html', '_blank', 'width=400,height=300');
});
</script>
</body>
</html>
弹出窗口(popup.html):
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<input type="text" id="messageInput" placeholder="输入消息">
<button id="sendMessage">发送消息到父窗口</button>
<script>
$('#sendMessage').click(function() {
var message = $('#messageInput').val();
if (window.opener && !window.opener.closed) {
window.opener.updateParentContent(message);
// 或者使用jQuery方式调用
// window.opener.$('#result').text('来自弹出窗口的消息: ' + message);
} else {
alert('父窗口已关闭或不可访问');
}
});
</script>
</body>
</html>
问题1:调用父窗口函数时报"Permission denied"错误
问题2:window.opener为null
问题3:父窗口jQuery函数未定义
没有搜到相关的文章