在JavaScript中,子窗体向父窗体传值通常可以通过以下几种方式实现:
window.opener
对象当一个窗口打开另一个窗口时,新打开的窗口可以通过window.opener
对象访问到打开它的窗口。
父窗体代码:
<!DOCTYPE html>
<html>
<head>
<title>Parent Window</title>
<script>
function receiveMessage(event) {
if (event.origin !== "http://example.com") { // 安全检查
return;
}
alert("Received message from child: " + event.data);
}
window.addEventListener("message", receiveMessage, false);
</script>
</head>
<body>
<button onclick="openChild()">Open Child Window</button>
<script>
function openChild() {
window.childWindow = window.open("child.html", "Child Window", "width=300,height=200");
}
</script>
</body>
</html>
子窗体代码(child.html):
<!DOCTYPE html>
<html>
<head>
<title>Child Window</title>
<script>
function sendMessage() {
window.opener.postMessage("Hello from child!", "http://example.com");
window.close();
}
</script>
</head>
<body>
<button onclick="sendMessage()">Send Message to Parent</button>
</body>
</html>
localStorage
或sessionStorage
子窗体和父窗体可以共享localStorage
或sessionStorage
中的数据。
父窗体代码:
<!DOCTYPE html>
<html>
<head>
<title>Parent Window</title>
<script>
function checkStorage() {
setInterval(() => {
const message = localStorage.getItem('messageFromChild');
if (message) {
领取专属 10元无门槛券
手把手带您无忧上云