LCJ
LCJ

Reputation: 22652

Close Browser window while unloading

I have MyPage.aspx html page (generated using ASP.Net). When user tries to navigate away from this page, I need to close the window – user should not be able to go back or navigate to another page.

When I used window.close() inside window.onbeforeunload event, it asks for a confirmation to the user. “The webpage you are viewing is trying to close the window. Do you want to close the window?” On clicking “No” the user can escape the close attempt. Is there any way to forcefully close the window without giving an option to the user?

Reference:

  1. How can I close a browser window without receiving the "Do you want to close this window" prompt?
  2. Html javascript to open new window and close current window
  3. "Unknown Exception" when cancelling page unload with "location.href"
  4. Display confirmation popup with JavaScript upon clicking on a link

Upvotes: 1

Views: 684

Answers (3)

David Hellsing
David Hellsing

Reputation: 108500

You can "trick" the browser like this:

window.onbeforeunload = function() {
    window.open('', '_self', '');
    window.close();
}

It seems to work in chrome/safari/ie/ff: http://jsbin.com/olijig/1

Firefox seems stubborn, but there might be another way to do the same in FF.

I should probably say that this technique is in no way standard and I don’t recommend it at all, and this code might break in many browsers besides firefox.

UPDATE

It actually works in Firefox too (latest version), but not older versions (I tried 3.6.1). You need to do some more testing to confirm the browser compatibility.

Upvotes: 3

Adam Plocher
Adam Plocher

Reputation: 14233

I'm not positive about this, but I believe if you have a window open another window, the parent window can close that child window. Would it be practical to have a landing page that opens your app in a separate window that could then close the window through javascript? Someone can probably elaborate more, as I haven't done this myself.

Upvotes: 1

Oscar
Oscar

Reputation: 13960

No, you can't. The user must be always capable of controlling whatever happens in his browser.

Upvotes: 1

Related Questions