Display something when trying to close my site

Asked

Viewed 3,240 times

10

It is possible to display something (a Alert, or a popup, an optin catcher(newsletter)) when the person tries to close mine website?

I’ve seen something like it, that it displays a alert() to confirm whether the person wanted to leave or stay at the website. But it only worked on Chrome!

  • 2

    Please think carefully before doing this on a website: unnecessary use hurts usability! Users appreciate. ;-)

1 answer

10


You can use the 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 it working here in 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?';
};
  • 1

    Perfect, I saw that in Firefox the message is not displayed, only the default confirmation that the browser does to the user.. Now, for study purposes, how can I pick up that person clicked on to continue on the site, and display something on the screen for her?

  • 1

    @Alexandrec.Caus the only thing that occurs to me is to use a timeout to show/run code to whoever decides to stay. Something like this: http://jsfiddle.net/nb2mqce0/

  • Interesting, now goes a question: window.onbeforeunload = function (e) {
 setTimeout(function () {
 document.getElementById('obrigado').style.display = 'block';
 }, 1000);
 return 'Tem a certeza que quer fechar a janela?';
}; When using this code, it works perfectly, but.. why it doesn’t just work like this: window.onbeforeunload = function (e) {
document.getElementById('obrigado').style.display = 'block';
return 'Tem a certeza que quer fechar a janela?'; }; That is, without this setTimeOut();..

  • 1

    @Alexandrec.Caus thus works but shows at the same time that the box with the question appears and is not as elegant. http://jsfiddle.net/vfdpntuo/

  • True, nice this site jsfiddle.. I tested it in my browser, and it didn’t take.. Must be something, I appreciate so your help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.