GordonBy
GordonBy

Reputation: 3397

Prompting and preventing user from navigating away/closing a page

As per how StackOverflow does it when you are adding a question or replying to a question;

I'd like to prompt the user with a;

"Are you sure you want to navigate away from this page"
"Press OK to continue or Cancel to stay on this page"

I've tried a couple of js snippets i've found on ze internet, but nothing quite cuts the mustard.

Upvotes: 4

Views: 6791

Answers (1)

RichieHindle
RichieHindle

Reputation: 281405

You need to implement window.onbeforeunload and return your message from it as a string:

window.onbeforeunload = function() {
    if (theUserHasStartedEditing) {
        return "You have started writing or editing a post."
    }
}

There's an online demo here: https://web.archive.org/web/20210619174356/https://www.4guysfromrolla.com/demos/OnBeforeUnloadDemo2.htm

Upvotes: 7

Related Questions