0

Can anyone tell me how i could use a global scope variable 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>
asked Jul 12, 2011 at 21:51

3 Answers 3

1

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();
}
answered Jul 12, 2011 at 21:53
Sign up to request clarification or add additional context in comments.

2 Comments

it will close the parent window not his sibling
I see. Thanks for the eye opener.
0

use window.opener.mywindow.close() from second window to close first . Choose other variable name for second window object

answered Jul 12, 2011 at 21:53

2 Comments

mmmm.. yes, i've tried that. doesn't seem to work. maybe i was doing it wrong? suggestions anyone?
window.opener.mywindow.close() is not working. Don't think so. It must work. Remember to create different variable for both window
0

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();
answered Jul 12, 2011 at 21:54

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.