0

I'd like to run some javascript whenever someone closes a browser tab but idk how that's possible.

I tried to do what https://stackoverflow.com/a/16707413/569976 described but it's not working for me:

$(window).on('beforeunload', function() {
    return confirm("Do you really want to close?");
});

(that's with jquery loaded)

Here's the JS fiddle: https://jsfiddle.net/hc9xrgvj/

Any ideas?

neubert
  • 15,947
  • 24
  • 120
  • 212
  • The `beforeunload` event is for the current `window` object (current tab). Are you also attempting to listen to other tabs closing? Are they tabs you [`open()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/open)ed or are they unrelated sites/files? – D M Jun 01 '21 at 19:10
  • 1
    Also, which browser(s) are you targeting? There are [known consistency issues](https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event#usage_notes) with `beforeunload`. – D M Jun 01 '21 at 19:11

1 Answers1

2

According to Mozilla:

According to the specification, to show the confirmation dialog an event handler should call preventDefault() on the event.

However note that not all browsers support this method, and some instead require the event handler to implement one of two legacy methods:

assigning a string to the event's returnValue property
returning a string from the event handler.

Some browsers used to display the returned string in the confirmation dialog, enabling the event handler to display a custom message to the user. However, this is deprecated and no longer supported in most browsers.

To combat unwanted pop-ups, browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with, or may even not display them at all.

The HTML specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event.

Caleb George
  • 234
  • 1
  • 10