Last active
July 11, 2025 13:19
-
-
Save kirkegaard/cc35b79f71156038a49f05f87196a227 to your computer and use it in GitHub Desktop.
Send post messages back and forth between windows
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8" /> | |
<meta name="viewport" content="width=device-width, initial-scale=1" /> | |
<title>Window 1</title> | |
<style> | |
body { | |
font-family: Arial, sans-serif; | |
margin: 20px; | |
} | |
button { | |
margin-right: 10px; | |
padding: 10px 15px; | |
font-size: 16px; | |
border-radius: 10px; | |
background-color: #007bff; | |
color: white; | |
border: none; | |
cursor: pointer; | |
&:hover { | |
background-color: #0056b3; | |
} | |
} | |
textarea { | |
width: 100%; | |
font-family: monospace; | |
font-size: 14px; | |
} | |
</style> | |
</head> | |
<body> | |
<button id="btn-send">Send message</button> | |
<button id="btn-open">Open window</button> | |
<button id="btn-close">Close window</button> | |
<h2>Messages</h2> | |
<textarea | |
id="message" | |
rows="10" | |
cols="50" | |
placeholder="Messages will appear here..." | |
></textarea> | |
<script> | |
const messageArea = document.querySelector("#message"); | |
let paymentWindow = null; | |
document.querySelector("#btn-open").addEventListener("click", () => { | |
paymentWindow = window.open("index.html", "paymentWindow"); | |
}); | |
document.querySelector("#btn-send").addEventListener("click", () => { | |
if (paymentWindow) { | |
paymentWindow.postMessage("Hello from Window 1", "*"); | |
} else if (window.opener) { | |
window.opener.postMessage("Hello from Window 2", "*"); | |
} else { | |
messageArea.value += "No window to send message to.\n"; | |
} | |
}); | |
document.querySelector("#btn-close").addEventListener("click", () => { | |
if (paymentWindow) { | |
paymentWindow.close(); | |
paymentWindow = null; | |
} else { | |
messageArea.value += "No window to close.\n"; | |
} | |
}); | |
window.addEventListener("message", (event) => { | |
messageArea.value += `Received: ${event.data}\n`; | |
}); | |
if (window.opener) { | |
setTimeout(() => { | |
window.opener.postMessage("Hello from Window 2", "*"); | |
}, 2000); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment