-2

Edit: This question is different as I am asking for a solution in 2017 browser. The other question relates to browsers years ago. Also it gives no solution. There must be some sort of solution, and that is what I am asking for.

I have added an event listener:

addEventListener("beforeunload", MyBeforeUnload, false);

I have my function:

function MyBeforeUnload() {
    if(!g_IsSaved) {
        return "You have not saved your data. If you leave this page without saving, your data will be lost.";
    }else {
    // Do not return anything if ok to leave
    }
}

This triggers and displays a warning message in IE.

It triggers the function and correctly returns the string, BUT does not fire the warning message in Chrome, Edge or Firefox when closing the browser with the [x] button in the top right of the browser.

Is it possible to get this working cross-browser in 2017?

Rewind
  • 2,554
  • 3
  • 30
  • 56
  • 1
    Nothing has changed since the last few times this was asked. See also http://stackoverflow.com/q/11317573/215552, http://stackoverflow.com/q/4683221/215552, http://stackoverflow.com/q/38879742/215552, http://stackoverflow.com/q/1921941/215552 – Heretic Monkey Mar 17 '17 at 19:03
  • The first link in Mike's 2nd comment has a particularly good answer as to why this isn't possible. – BSMP Mar 17 '17 at 20:04
  • The question is the same, even if answers changed. We want to update answers to an existing question (if they can be updated), not spawn new copies of the question. – Jukka K. Korpela Mar 17 '17 at 21:47

1 Answers1

0

Try to use it like that it should work in cross-browser

window.addEventListener("beforeunload", function(e) {
    var confirmationMessage = "You have not saved your data. If you leave this page without saving, your data will be lost.";

    if (!g_IsSaved) {
        (e || window.event).returnValue = confirmationMessage; //Gecko + IE
        return confirmationMessage; //Webkit, Safari, Chrome etc.
    } else {
        // Do not return anything if ok to leave
    }
});


But Chrome have decided to remove the ability to set a custom message in the onbeforeunload dialog to avoid scamming

See this bug report from the 18th of February, 2016.

onbeforeunload dialogs are used for two things on the Modern Web:
1. Preventing users from inadvertently losing data.
2. Scamming users.

Ahmed Essawy
  • 326
  • 4
  • 13
  • Thanks for the idea, but this seems to stop even IE from working. – Rewind Mar 17 '17 at 19:20
  • 1
    Chrome have decided to remove the ability to set a custom message in the `onbeforeunload` dialog to avoid scamming & preventing users from inadvertently losing data. – Ahmed Essawy Mar 17 '17 at 19:38