0

I'm detecting window closed this way, and It works but I can't execute a function.

function myFunc(){
   alert("byebye");
}
window.onbeforeunload = function (event) {
    myFunc(); //Error, it doesn't execute
    return "Bye"; //It works, it shows an alert.
};

How can I call myFunc when I'm closing a window/tab?

ProtectedVoid
  • 1,293
  • 3
  • 17
  • 42

2 Answers2

1

Try this by replacing alert by return.

function myFunc(){
   return "byebye";
}
window.onbeforeunload = function (event) {
    myFunc(); //Error, it doesn't execute
    return "Bye"; //It works, it shows an alert.
};
CodePhobia
  • 1,315
  • 10
  • 19
0

You can't call functions at the onbeforeunload event, you can only pass a string that is shown to the user.

Michael
  • 116
  • 6
  • Sorry - I was too fast - you can pass a function, but this function must return a string. See also https://developer.mozilla.org/de/docs/Web/API/WindowEventHandlers/onbeforeunload – Michael Aug 27 '15 at 14:00
  • What if I want a function to modify the UI instead of showing a message? I'm in trouble with that – ProtectedVoid Aug 27 '15 at 14:15
  • Unfortunately you can't do anything else than showing a message when closing a window. – Michael Sep 02 '15 at 08:18