Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I programmatically detect how a browser handles window.close()?

Different web browsers handle the window.close() function differently. IE prompts the user for confirmation, while Firefox and Safari just fail to honor it unless the window was originally opened with Javascript and display a message saying as much in the console.

A third party web application used internally in our organization that I support displays a 'close' button at the end of a wizard-like series of pages. This works well for IE, which is what the majority of our users use. However, this obviously fails in FF. I'd prefer to leave the button in and use Javascript to gracefully degrade the UI by not displaying that button in any browser that will not perform the window.close().

As a rule of thumb, I try to check browser capability rather than relying on a hard-coded policy based on browser detection whenever possible. Is there a way to programmatically check the support for window.close() so I can determine whether the button should be displayed in the first place?

like image 299
Brahm Avatar asked Oct 24 '11 21:10

Brahm


2 Answers

Try this:

Demo: http://jsfiddle.net/ThinkingStiff/mnv87/

Script:

function hasClose() {

    var close = window.open( '', '', 'height=100,width=100,left=3500', false );
    close.close();
    return close.closed;

};

if( hasClose() ) {
    //show button
} else {
    //hide button
};

Note hasClose() will also return false if popups are blocked.

like image 84
ThinkingStiff Avatar answered Oct 14 '22 15:10

ThinkingStiff


Why not check compatibility, and then append if compatible? Using jQuery:

<script type="text/javascript" src="latest_jquery_file.js"></script>
<script type="text/javascript">
  $(document).on("ready", (function(e)
  {
   $("body").append('<p><a href="#" id="windowcloser">Close The Window!!</a></p>');
      $('#windowcloser').click(function(){
         window.close();
      });
  })
  );
</script>

Since jQuery is cross browser compatible, it should

like image 31
sablefoste Avatar answered Oct 14 '22 16:10

sablefoste