I would like to execute a function before leaving page without showing a confirmation popup with Javascript only. I've tried with the code below but it didn't work or with the onbeforeunload but it always shows the popup.
var result = 'test'; if(window.onbeforeunload == true) { result = 'test1'; alertmess(); } function alertmess() { alert(result); } //window.onbeforeunload = function() { // return result; //}
onbeforeunloadevent can only be used to trigger that popup, it can't be used for anything else. Your only options for something like this are to attach an event to every outbound link on your page. However, there is no way to directly capture an event for someone leaving via other means (manually typing a url, closing the tab etc).According to the specification, to show the confirmation dialog an event handler should call preventDefault() on the event. The HTML specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event. See the HTML specification for more details. from developer.mozilla.org/en-US/docs/Web/API/Window/…