You don't need the postMessage API for a popup window being used this way.
//Inside parent window
var data = {age: 10}; //No quotes around age
window.open('http://localhost:8080/index2.html');
//Inside popup window
var sameData = window.opener.data;
Admittedly though, you probably shouldn't use a popup window through window.open(...), since they get blocked all the time.
If you go with an iframe modal, you might be able to get the postMessage
way to work by doing something like
//In iframe
window.addEventListener("message", iframeReceiveMessage);
document.addEventListener("DOMContentLoaded", function() {
//JSON data for message
window.parent.postMessage("iframe is ready", "http://localhost:8080");
});
function iframeReceiveMessage(event) {
var iframeData = JSON.parse(event.message);
//iframeData.age === 10
}
and then listening in the parent with:
//In parent
window.addEventListener("message", parentReceiveMessage);
function parentReceiveMessage(event)
{
if (event.origin !== "http://localhost:8080" && event.message !== "iframe is ready") { return; }
var iframe = document.getElementById("iframeId").contentWindow,
parentData = {age: 10};
iframe.postMessage(JSON.stringify(parentData), "http://localhost:8080");
}
Since some browsers only accept strings in the postMessage response so you'd have to convert your data to JSON.
Still, it's probably overkill for sending object data. If you're already on the same domain, have you thought about using sessionStorage?
https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
You'll still have to use JSON.stringify and JSON.parse (sessionStorage only stores strings), but it's pretty simple:
//Store it
var data = {age: 10};
sessionStorage.data = JSON.stringify(data);
//Use it
var newData = JSON.parse(sessionStorage.data);
//Remove it
sessionStorage.removeItem("data");
One drawback to this method is that sessionStorage is separate for HTTPS pages, so you can't send sessionStorage data between the two protocols!