Last active
May 11, 2025 16:35
-
-
Save terremoth/b1ed183954dc702a14f8d543444d15ad to your computer and use it in GitHub Desktop.
Father - child html page communication with JavaScript postMessage
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> | |
<head> | |
<title>Child Window</title> | |
<meta charset="utf-8"> | |
</head> | |
<body> | |
<h2>Child</h2> | |
<input type="text" id="valueToSend" placeholder="Enter something..." /> | |
<button onclick="sendMessage()">Send to Parent</button> | |
<script> | |
function sendMessage() { | |
const value = [document.getElementById('valueToSend').value, 1, 3, 4]; | |
if (window.opener) { | |
window.opener.postMessage(value, window.location.origin); // Change origin if needed | |
window.close(); // optional | |
} | |
} | |
</script> | |
</body> | |
</html> |
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> | |
<title>Index</title> | |
<meta charset="utf-8"> | |
</head> | |
<body> | |
<h2>Index</h2> | |
<input type="text" id="inputFromChild" placeholder="Waiting for message..." /> | |
<button onclick="openChild()">Open Popup</button> | |
<script> | |
function openChild() { | |
const params = 'width=400,height=300,resizable=no,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,fullscreen=no,top=100,left=100'; | |
const show_window = window.open('child.html', 'popup', params); | |
show_window.focus(); | |
} | |
window.addEventListener('message', function (event) { | |
// Always check origin for security | |
if (event.origin !== window.location.origin) { | |
console.warn("Blocked message from unknown origin:", event.origin); | |
return; | |
} | |
// Set received value in input | |
document.getElementById('inputFromChild').value = event.data[1]; | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment