The Blind Hawk
The Blind Hawk

Reputation: 1666

JS onbeforeunload runs unconditionally to user's selected choice

I have a very simple code:

window.onbeforeunload = function(e) {
    console.log("closing");
    e.preventDefault();
    try { self.recorder.stop(); } 
    catch (err) { console.log(err); }
    return "custom message here";
}

What I need is to run the recorder.stop() only if the user presses yes, and actually unloads the page.
What I tried:

onpagehide

I found out that onpagehide actually runs console.log("closing") but not recorder.stop() for some reason. Possibly because it runs in the "terminated" state, and no async tasks can run in the terminated state.

onbeforeunload

The popup shows, and the code runs, however the code also runs if the user presses "cancel", and decides not to unload the page.

onunload

The code simply does not run.
I have a console.log() inside my recorder.stop() function, and tried it with the "keep logs" functionality from the inspector.

onvisibilitychange

This one looked promising, but I can't find the right state for it.

document.visibilityState === 'hidden'

Runs anytime I switch to another window, even without closing the previous one.

document.visibilityState === 'terminated'

Most probably won't work, for the same reason as onpagehide()

document.visibilityState === 'frozen'

Doesn't work, probably because the page does not freeze before terminating.

Upvotes: 0

Views: 99

Answers (0)

Related Questions