-1

I have a page that has a exit page confirmation box which is this code

<script>
window.onbeforeunload = function() {
        return 'You have unsaved changes!';
}
</script>

Now, i want to add a redirection. For example i close the page, a confirmation box will appear that has a Leave and Cancel button. When Cancel is clicked it will redirect to a page. Then, when Leave button is click a page will just close.

Please Help..

JUNYXER
  • 1
  • 1
  • Possible duplicate of [Is there a callback for cancelling window.onbeforeunload](https://stackoverflow.com/questions/11835217/is-there-a-callback-for-cancelling-window-onbeforeunload) – Robby Cornelissen Aug 23 '18 at 09:02
  • @RobbyCornelissen Actually I believe this question does not answer OP's problem. – Krzysztof Janiszewski Aug 23 '18 at 09:07
  • Possible duplicate of [confirm() on window.onbeforeunload](https://stackoverflow.com/questions/12132060/confirm-on-window-onbeforeunload) – Supreme Dolphin Aug 23 '18 at 09:12
  • You're just not passing the event parameter into the function. You should do something like `window.onbeforeunload = function(event){ ... });` – Supreme Dolphin Aug 23 '18 at 09:15
  • @KrzysztofJaniszewski OP asks about how to react to the user cancelling the dialog that is triggered by the `onbeforeunload` event. The duplicate question asks exactly the same. – Robby Cornelissen Aug 23 '18 at 09:20

2 Answers2

0

Unfortunatelly this is impossible. The only way to prevent closing or refreshing the page is by using beforeunload event.

The little trick I used was to bind an event to all a tags on my page and to F5 button, that displays a modal with confirmation. And then if cancelbutton was clicked I would prevent the default action. So page was not refreshed or redirected.

But as to closing the tab there is no way to achieve what you would want. It's a pitty though because many people struggle with this.

Krzysztof Janiszewski
  • 3,763
  • 3
  • 18
  • 38
  • how about... when closing tab a confirmation box will appear that has **Close** and **go to this page**? I tried adding 'window.location' on my code but it doesn't work – JUNYXER Aug 23 '18 at 09:28
  • As I said, this is not possible. Sorry.. I know because I spent many hours on a very similar problem. – Krzysztof Janiszewski Aug 23 '18 at 10:55
0

Try something like this:

if (typeof window.addEventListener === 'undefined') {
    window.addEventListener = function(e, callback) {
        return window.attachEvent('on' + e, callback);
    }
}

window.addEventListener('beforeunload', function() {
    return 'Dialog Text Here';
});

If that doesn't work, then you can try something really simple like this:

window.onbeforeunload = function(e) {
    return 'Dialog text here.';
};

Check MDN for some useful documentation. If you need to customize it further, use plugins like bootbox for that. Check this answer too and the possible duplicates linked below your question.

Supreme Dolphin
  • 2,248
  • 1
  • 14
  • 23