0

I need to use onbeforeunload everywhere, when user leave my site.

var leave_message = 'Leave message';
var validNavigation;
function goodbye(e) {
    if (!validNavigation) {
            if (!e) e = window.event;
            e.cancelBubble = true;
            e.returnValue = leave_message;
            if (e.stopPropagation) {
                e.stopPropagation();
                e.preventDefault();
            }
            return leave_message;
    }
}

$("body").on('click', 'a', function () {
    validNavigation = true;
});

window.onbeforeunload = goodbye;

But there is many places in my javascript, where i use window.location for redirecting user to internal pages. And i tired of pasting validNavigation = true; in these parts of code.

Please give me advice how i can setup it globally?

sandra1n
  • 133
  • 1
  • 1
  • 10
  • 1
    put in a separate js file and make a reference in the head. – Jai Feb 09 '15 at 10:02
  • Hello @Jai, can you explain? As you can see i asked about cases when i need to cancel onbeforeunload... – sandra1n Feb 09 '15 at 10:07
  • 1
    You can't cancel `on(before)unload` event, hence all the code for canceling the event is useless in the posted snippet. Also, there's no way to detect the element or script/function which has triggered an unload event in its handler, so you've just handle this before the handler will be executed. – Teemu Feb 09 '15 at 10:08
  • @Teemu, this is a little bit tricky when in my code everywhere i need to use overriding this variable...you don't think so? – sandra1n Feb 09 '15 at 10:11
  • I think I can understand what you need, but unfortenately the answer is [still no](http://stackoverflow.com/q/291553/1169519). Though there's also [this answer](http://stackoverflow.com/a/13916847/1169519), but I'm not sure if you can use it. – Teemu Feb 09 '15 at 10:20

0 Answers0