Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confirmation before closing of tab/browser

People also ask

How do I get Chrome to verify before closing?

Select 'Settings' from the drop-down menu. Click the 'Extensions' tab, locate 'Chrome Toolbox by Google,' and then click the 'Options' link under the description of the extension. Check the box next to 'Confirm Before Closing Multiple Tabs' in the 'Tabs' section to automatically update your browser's settings.

How can I tell if my browser is closed?

A tab or window closing in a browser can be detected by using the beforeunload event. This can be used to alert the user in case some data is unsaved on the page, or the user has mistakenly navigated away from the current page by closing the tab or the browser.

How do I know if browser or tab closed in react?

To handle the browser tab close even in React: Use the useEffect hook to add an event listener. Listen for the beforeunload event. The beforeunload event is triggered when the tab is about to be unloaded.


Try this:

<script>
window.onbeforeunload = function (e) {
    e = e || window.event;

    // For IE and Firefox prior to version 4
    if (e) {
        e.returnValue = 'Sure?';
    }

    // For Safari
    return 'Sure?';
};
</script>

Here is a working jsFiddle


Try this:

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

more info here MDN.


I read comments on answer set as Okay. Most of the user are asking that the button and some links click should be allowed. Here one more line is added to the existing code that will work.

<script type="text/javascript">
  var hook = true;
  window.onbeforeunload = function() {
    if (hook) {

      return "Did you save your stuff?"
    }
  }
  function unhook() {
    hook=false;
  }

Call unhook() onClick for button and links which you want to allow. E.g.

<a href="#" onClick="unhook()">This link will allow navigation</a>

The shortest solution for the year 2020 (for those happy people who don't need to support IE)

Tested in Chrome, Firefox, Safari.

function onBeforeUnload(e) {
    if (thereAreUnsavedChanges()) {
        e.preventDefault();
        e.returnValue = '';
        return;
    }

    delete e['returnValue'];
}

window.addEventListener('beforeunload', onBeforeUnload);

Actually no one modern browser (Chrome, Firefox, Safari) displays the "return value" as a question to user. Instead they show their own confirmation text (it depends on browser). But we still need to return some (even empty) string to trigger that confirmation on Chrome.

More explanations see on MDN here and here.