javascript – Display something when trying to close my site

Question:

Is it possible to display anything (an alert , or a popup , an optin( newsletter ) catcher) when the person tries to close my site ?

I've seen something like that, that it displays an alert() to confirm if the person wants to leave or stay on the site . But it only worked on Chrome!

Answer:

You can use window.onbeforeunload .

So when you close the window you get a question with the text you choose, for example 'Are you sure you want to close the window?'.
You can see the same at work here on the OS when you close a page with a question or answer that is in the middle of editing and has not been saved/saved.

window.onbeforeunload = function(e) {
   return 'Tem a certeza que quer fechar a janela?';
};
Scroll to Top