Onunload methods and onbeforeunload do not work

Asked

Viewed 3,792 times

0

Based on that reply i would like when the user closes the tab(or updates) to receive an Alert saying Tchau, but only when I enter the page he tells me Olá, when I upgrade or close the flap, it doesn’t tell me Tchau.

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    </head>
</html>

<script type="text/javascript">
    window.onload = function(){alert('Olá')};
    window.onbeforeunload = function(){alert('Tchau')};
    window.onunload = function(){alert('Tchau')};
</script>

Remembering that I’ve tried that way too

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    </head>
</html>

<script type="text/javascript">
    window.onload = function(){alert('Olá')}
    window.onbeforeunload = function(){return 'Tchau';}
    window.onunload = function(){return 'Tchau';}
</script>

2 answers

4


I answered a similar question here.

But for the method window.onbeforeunload work, you need to put a return:

window.onbeforeunload = function(){
  return 'Tchau';
}

However, some browsers do not display the message from return, but only its own confirmation box (if I’m not mistaken, Chrome, Firefox and Opera).

Edit

The method onunload is executed after the window is closed. So it will not display anything. Already the onbeforeunload does something before closing.

View documentation on MDN.

Edit 2

The method window.onbeforeunload will only work if there is some interaction on the page. If the user opens the page and closes it without having done any interaction, there will be no confirmation.

Edit 3

Instead of making a window.onload, you can create a modal of welcome and force the user to click, generating an interaction. See the code (online test on this link):

#tela {
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    position: fixed;
    background-color: rgba(0, 0, 0, 0.6);
    z-index: 999;
    display: flex;
    justify-content: center;
}

#aviso{
   width: 300px;
   padding: 20px;
   background-color: #fff;
   border-radius: 10px;
   z-index: 999;
   top: 50%;
   align-self: center;
   text-align: center;
}
<div id="tela">
   <div id="aviso">
      Olá!
      <br /><br />
      <input type="button" value="OK" onclick="document.querySelector('#tela').style.display = 'none';" />
   </div>
</div>

  • I just edited the question, I tried it that way and I couldn’t either.

  • And is there any way to test if it’s working on google Chrome ??

  • @Lucascarezia works perfectly. See a test page at this link. Try to exit by clicking on the link, reload the page or close the tab.

  • You had commented another method, however deleted the comment, could put it again ??

  • @Lucascarezia where?

  • Right here, you told me to test another method (other than onunload and onbeforeunload) in Chrome, but you deleted the comment, and I was curious when to method.

  • @Lucascarezia Isn’t the link in the answer? https://answall.com/a/263488/8063

  • Just for the record: the ability to define a {String} to the event "onbeforeunload" was removed in the Chrome 51, Safari 9.1 and Firefox 4

  • @Lauromoraes Pois eh, Chrome, FF and Opera (if I’m not mistaken) ignore strings. They show their own confirmation box.

  • @dvd It was a method window.algumacoisa same. But no problem. Is there any way to capture the Unload event even with the user not interacting with the page ?? (if you prefer I open another question).

  • @Lucascarezia Wait a little while I’ll see... I’ll be right with you

  • From the Chrome 60 and Firefox 44 respectively the events "beforeunload" and "onbeforeunload" require the user to have at least one interaction with the page

  • @Lauromoraes And there’s no way to "circumvent" it ??

  • No. This is default browser implicit in your "politics". The correct would be to follow the @dvd response and align to a strategy that makes the user interact at least once with the page.

  • @Lucascarezia I believe there is no way. The browser blocks any attempt to circumvent this, even simulating interaction.

  • All right, I’ll do it. Thanks for your help.

  • @You’re welcome to Lucascarezia. Then, with more time, I’ll explore more of this, I think it’s a bit cheesy. I’ll let you know.

  • @Perfect DVD, I’m waiting.

  • @Lucascarezia I put an update in the reply. It’s a way to force the user to click on the page.

Show 14 more comments

2

I’ve talked about this a few times:

To summarize the answers, onunload and onbeforeunload do not serve to detect when the person leaves the site, what it does is to detect the unloading, that is if browsing a link from the same site will trigger the event, if press F5, will trigger the event, if using the Back or Forward will trigger the event.

Still if you want to use, you must first understand some things, when Unload or beforeunload occurs the page already in pre-process of destroying/downloading and therefore no new windows/Guis will be generated.

That is to say, alert(), confirm(), prompt() and window.open() will not run, even if you wish, this is explained in the W3C specification https://www.w3.org/TR/html5/webappapis.html#user-prompts

note: Alert/confirm and others are also ignored in the event pagehide

So the only event you should use is the beforeunload with the return '<string>';, has one more problem your HTML this badly marked, it is not that it affects the execution, but still it should be this:

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    </head>
    <body>
        <script>
            //script vai aqui
        </script>
    </body>
</html>

However note that even using:

window.onbeforeunload = function(){
    return 'Tchau';
};

Will not issue the desired text, he will only generate a standard message asking whether or not to download the page:

janela de confirmação de saida com o evento beforeunload

In other words, this is not just a "goodbye" message, nor is the Tchau, is a resource to be used on certain occasions, to say goodbye is certainly not a good way to implement this.

Providing a good user experience

Say hi, say goodbye, is this really necessary? Does the user not know he is already leaving or when he entered the page?

I personally believe that these types of messages sound more like noise than something useful to the user, so much so that for many of these problems is that certain implementations have been removed from the browsers, many more things cause that sensation "to no, again that message", than really seem polite, the user will feel welcome on the site when he gets what he wants from the site, and not with a disturbing welcome message that hangs everything until it is pressed on the button ok.

About the use of beforeunload and unload I explained, they are not to check when the person leaves the site, and there is no guaranteed way to do this, you can implement anything, detect internal and external links, but this kind of thing is unnecessary work, I personally recommend that you focus on creating a nice interface to navigate so that the user feels good when browsing, so yes he will feel welcome and when he leaves the site for sure he will want to come back.

What would be the beforeunload utility?

It would be more interesting if used to prevent you from losing edits made, or if it is a game to prevent you from leaving without saving the game, as this is exactly what the standard message says:

Wish to leave this site?

It is possible that changes made have not been saved

This is the focus of it currently, preventing the user from accidentally closing something and losing something.

  • 1

    Your reply was great, my intention with Hello and Bye was just testing, to see how the methods worked, but your reply was exceptional, thank you.

  • @Lucascarezia take advantage and read the links, when you can clear, on type check if the user is still online or not, using a timer

Browser other questions tagged

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