7

I want to prevent browser to close page in any case or in other case, Prevent browser to do anything when onbeforeunload is called. Here is my code which i have tried.

 (function() {
    var proxied = window.onbeforeunload;
    window.onbeforeunload = function(e) {
        e.preventDefault();
        e.stopPropagation();
            //i want to stop everything
        console.log('stay here');
        // return 'message';
    };
})();
  • I want to perform a action before leaving the page (disconnect the chat)
  • If you could prevent browsers from closing windows, I guess the internet would look very different. This is AFAIK. not possible – firelynx Jun 11 '15 at 12:42
  • is this a function call e.stopPropagation? because you are not () calling it – firelynx Jun 11 '15 at 12:45
  • Possible duplicate of [Prevent a webpage from navigating away using JavaScript](https://stackoverflow.com/questions/821011/prevent-a-webpage-from-navigating-away-using-javascript) – georgeawg Nov 04 '19 at 20:35

2 Answers2

11

You can't outright prevent a user from leaving the page (This would lead to much abuse on spam/advertisement sites who try to get you to stay on a page), but you can show things such as a window which causes a confirm prompt to the user. Have a look at Prevent a webpage from navigating away using JavaScript which can lead you to the right direction of what you're trying to accomplish.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Blue
  • 22,608
  • 7
  • 62
  • 92
  • I want to perform a action before leaving the page (disconnect the chat) –  Jun 11 '15 at 12:44
  • What framework are you using for chat? Are you trying to make an AJAX request? You will have to make sure you're not doing things like making requests asynchronously (Set them to synchronous), otherwise it will cancel the requests as the browser is attempting to leave the page. – Blue Jun 11 '15 at 12:48
  • i want to close the chat and notify other persons that (this person) user is leave the chat. –  Jun 11 '15 at 13:04
  • Like I mentioned, this is the function you want to do it in. Just replace `console.log` with what you're intending to do, and it should do it (As long as you're not making asynchronous requests) – Blue Jun 11 '15 at 13:09
3

There is no way to stop browser to close. The browser doesn't allow you to do that.

Blue
  • 22,608
  • 7
  • 62
  • 92
Ijaz Ahmed Bhatti
  • 736
  • 1
  • 7
  • 26