window.open global scope variable javascript
Can anyone tell me how i could use a global scope v开发者_如何学JAVAariable so that I could close "window 1" from "window2"?This is really throwing me for a loop, so any help would be great!
I have index.html with 1 link and 1 button. Button opens window 1, link opens window 2. I want Window 2 to have a button that can close window 1. Please help if you can!! Thanks!!!
<script type="text/javascript">
function openWin1()
{
myWindow=window.open('','','');
myWindow.document.write("<p><img src=\"flower.jpg\" /></p>");
myWindow.focus();
}
function openWin2()
{
myWindow=window.open('','','');
myWindow.document.write("<style type=\"text/css\">body{background-color:yellow;}</style>
<p><img src=\"bee.jpg\" /></p><input type=\"button\" onclick=\"window.close();\"
value=\"Close Window 1\" />");
myWindow.focus();
}
</script>
</head>
<body>
<input type="button" value="Window 1" onclick="openWin1();" /><br />
<a href="javascript:openWin2();">Window 2</a>
</body>
</html>
Tested this locally (works in Chrome, should work in other browsers too):
function openWin1() {
myWindow1 = window.open('google.com', '', '');
myWindow1.document.write("<p><img src=\"flower.jpg\" /></p>");
myWindow1.focus();
}
function openWin2() {
myWindow2 = window.open('yahoo.com', '', '');
myWindow2.document.write("<style type=\"text/css\">body{background-color:yellow;}</style><p><img src=\"bee.jpg\"></p><input type=\"button\" onclick=\"window.opener.myWindow1.opener = window.self;window.opener.myWindow1.close();\" value=\"Close Window 1\" />");
myWindow2.focus();
}
use window.opener.mywindow.close()
from second window to close first . Choose other variable name for second window object
Both "window1" and "window2" can refer to the original page via window.opener
. Your original page can therefore expose a global function that either of the other pages can call like this:
window.opener.closeTheOtherOne();
精彩评论