36

How to close a window using jQuery for all browser compatibility?

<input type="button" 
       name="backButton" 
       value="Close" 
       style="background-color:#245f91; color:#fff;font-weight:bold;" 
       onclick="window.close();">

This onclick event is working in IE. Could you help me to write code in jQuery?

ROMANIA_engineer
  • 51,252
  • 26
  • 196
  • 186
surya
  • 383
  • 1
  • 3
  • 5
  • 4
    window.close is plain javascript. Nothing in jQuery will make it more cross browser. It is the browser itself that decides if it allows your script to close the window. – mplungjan Jan 17 '12 at 06:15

5 Answers5

61
$(element).click(function(){
    window.close();
});

Note: you can not close any window that you didn't opened with window.open. Directly invoking window.close() will ask user with a dialogue box.

Shiplu Mokaddim
  • 54,465
  • 14
  • 131
  • 183
17

You can only use the window.close function when you have opened the window using window.open(), so I use the following function:

function close_window(url){
    var newWindow = window.open('', '_self', ''); //open the current window
    window.close(url);
 }
  • I think that should be "newWindow.close(url);". But in any case, this worked great and should be the accepted answer! – BrianLegg Feb 12 '16 at 15:03
  • Good answer. Yes, it should be "newWindow.close(url);". Why are you using the url parameter? – Mikel Aug 08 '17 at 13:14
  • Sadly does not work in Edge. Works current Chrome (but Chrome seems to let any old link close a window) and works with IE 11.... Bugger. – BeNice Jul 14 '19 at 20:35
17

just window.close() is OK, why should write in jQuery?

liunian
  • 430
  • 2
  • 6
4

For IE: window.close(); and self.close(); should work fine.

If you want just open the IE browser and type

javascript:self.close() and hit enter, it should ask you for a prompt.

Note: this method doesn't work for Chrome or Firefox.

nobody
  • 19,421
  • 17
  • 55
  • 76
Bajju
  • 895
  • 11
  • 27
1

This will only work for windows which are opened by using window.open(); method. Try this

var tmp=window.open(params);
tmp.close();
Zo Has
  • 12,193
  • 21
  • 81
  • 147