0

I want to close a browser window whether it is in open. Am new for javascript so help me to create the below logic using javascript. My JavaScript code is here:

if (myWindow.open() == true) {
    myWindow.close();
} else {
    myWindow=window.open('http://index.html',
                         'popUpWindow',
                         'height=700,width=800,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes'
                         );
}
Christoph
  • 50,121
  • 21
  • 99
  • 128
rom fernando
  • 71
  • 1
  • 5
  • 13

3 Answers3

0

Yes I agree with Christoph

if (!myWindow.closed) {
    myWindow.close();
} 

further more

Note: there is browser-specific differences with the above. If you opened the window with Javascript (via window.open()) then you are allowed to close the window with javascript if you have reference in your case you have that. Firefox disallows you from closing other windows. I believe IE will ask the user for confirmation. Other browsers may vary.

Afnan Bashir
  • 7,319
  • 20
  • 76
  • 138
0

You are close to the right result.

Just check for

(myWindow.closed === false) // same as (!myWindow.closed)

instead of

(myWindow.open() == true)

(since open() will just open another window and your check will fail.)

Also note, that you need to write index.html or http://sub.yourdomain.tld/index.html, but not http://index.html.

Christoph
  • 50,121
  • 21
  • 99
  • 128
0

Use closed property to check the window status, but first check whether the window object has been created or not.

var myWindow=null;
if (myWindow && !myWindow.closed) { //exist and is not closed
    myWindow.close();
    myWindow=null; //delete the object
} else { //not exist or is closed
    myWindow=window.open('http://index.html',
                         'popUpWindow',
                         'height=700,width=800,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes'
                        );
}
Jay
  • 4,627
  • 1
  • 21
  • 30