I’m not really a web developer, but today a friend asked me how to force close a browser window? And also without the infamous security measure (“Are you sure you want to close?”) taken by Microsoft in IE 7 and forward.
It goes without saying, that it is a local operation on the Client-side as we are talking about closing his browser. It can therefore not happen server side (really..?). The only option we are left with is to execute some script in the browser, or to let the Client download a browser plug-in that forces the browser to close. Well – I took the easy path and went for the scripting option.
According to Google, I’m not the only one with this problem! A number of other dudes have faced the same problem. The recipe (1) they used proved not to work in my case. I found only one solution that actually worked (2).
The trick is to let the browser believe that the browser window has been opened by JavaScript in the first place. If the browser believes, that the window is the initial window (window.opener = null), it will ask for a confirmation from the User. If the browser on the other hand believes, the window has been opened by JavaScript (and thereby carrying an '.opener'), it will close without prompting. This should actually make option (1) work as you explicitly set the owner, but for some reason unknown to me, it did not work at all in my IE8 browser. Option (2) works like a charm instead!
(1) This does not work for me. You are still present with a dialog using this option (IE 8).
function closeWin() {
window.opener = ''x'';
window.close();
}
(2) This WORKS!
function closeWin() {
window.open('', '_self', '');
window.close();
}
Invoking this last function from a client side button (html button), will close the browser without asking any questions or presenting any warnings. I suspect the reason is that you open the windows “into itself” so to speak. The current window has therefore been opened by JavaScript, which allows IE to close the window without prompts.
Neat work, but still somewhat bizarre workaround :-)