In my web page I use this function to show a small pop up Window
function popup (url)
{
poppedUpWindow= window.open(url, "PopupWindow", "width=400,height=300");
poppedUpWindow.focus();
return false;
}
I need to share objects between thoos 2 windows. I tried doing something like this but it does now work
poppedUpWindow.document.documentElement.addEventListener("load", foo, false);
Is also possible that I do something like this
function popup (url)
{
poppedUpWindow= window.open(url, "PopupWindow", "width=400,height=300");
var tmp = poppedUpWindow.document;
tmp.write('<html><head><title>popup</title>');
....
tmp.close();
poppedUpWindow.focus();
return false;
}
But this approach will make solving the problem much harder. So how should I transfer information from the parent window to the popped up window and vice versa?
From the documentation for postMessage :
Send a message like this:
otherWindow.postMessage(message, targetOrigin);
otherWindow can listen for dispatched messages by executing the following JavaScript:
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event)
{
if (event.origin !== "http://example.org:8080")
return;
// ...
}
Keep in mind browser support: http://caniuse.com/#feat=x-doc-messaging
IE 8+, Firefox 3+, Chrome all versions, Opera 9.5+, Safari 4+
Here is how I solved the issue for anyone else facing the same issue. I am considering the browser to be either chrome or firefox. I did not test other browsers. The event "load" in Chrome sometimes gets fired before the whole javascript files loads.
function popup (url)
{
poppedUpWindow= window.open(url, "PopupWindow", "width=400,height=300");
poppedUpWindow.focus();
if(is_chrome)
{
window.setTimeout("doSomething()",300); //this value could vary! 300ms seemed fine to me!
}
else
{
fenster.addEventListener('load', doSomething, true); // FireFox
}
return false;
}
function doSomething()
{
poppedUpWindow.postMessage("hi","*");
var a = poppedUpWindow.document.getElementById("b");
// do anything you want..
}
In the other html there should be this method
function receiveMessage(event)
{
if (event.origin !== stringUrlOfFirstWebPage)
{
return;
}
event.source.postMessage("hey!",event.origin);//talking back to the first web page
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.