Run script js when trying to close the window

Asked

Viewed 10,050 times

5

I have a form that is a popup (overlapping div)

<div class="bloco-newsletter" style="background-image: url(http://bhpump.izap.ws/plus/imggen/imageChangeColor/005873/bg-newsletter.png)">

    <div class="newsletter-title">NEWSLETTER</div>

    <form action="http://bhpump.izap.ws/plus/modulos/perfil/registrar_newsletter.php" method="post">
        <input type="hidden" name="op" value="register">

        <div class="text">Não saia ainda, temos ofertas exclusivas para você! Deixe seu e-mail aqui.</div>
                        <input class="ipt-newsletter" type="text" name="plus_email" value="" maxlength="60" data-placeholder="E-MAIL">


        <div class="btn-assinar">
            <img class="vermais_left pull-left" src="http://bhpump.izap.ws/plus/imggen/imageChangeColor/005873/btn-left-style.png" alt="">
            <input class="vermais_middle pull-left" style="background-color: #005873" name="ok" type="submit" value="ASSINAR">
            <img class="vermais_right pull-left" src="http://bhpump.izap.ws/plus/imggen/imageChangeColor/005873/btn-right-style.png" alt="">
        </div>
    </form>
</div>

This form is hidden, I want when trying to close the window open this form and only close the window if you click on Submit or close the popup

I tried that plus the window and shut:

global $xTema;
$xTema->addJSOnReady('
$(window).unload(function(){
$("#modal_24").modal("show");
});
');
  • Take a look here

  • The correct event is the unonload.

  • @Walkerleite Plus I just want to show a window like this one for confirmation, and kind of replace it

  • Possible duplicate of Capture event close window

  • @Danielomine is not quite a duplicate, the problem he wants to fire a Modal similar to that of the bootstrap at the time of trying to close, the situation goes beyond. It is better to close as typing error (due to it having called a method that does not exist).

  • @Guilherme Nascimento, the question is different but the answer is the same. About the action after blocking the closure, it would be secondary question.

  • @Danielomine I’m not talking about the question, the resolution is different, there does not say that DOM elements are not fired after the unonload, there is just an explanation of how to capture the "event". Here the question is about displaying a modal that is HTML (DOM) and the answer here explains why it doesn’t work. Both the question is different, as the answer does not cover the situation, I hope you understand as a constructive criticism ;)

  • but that is exactly the crux of the matter... knowing how to do this, you will be able to proceed with the rest.. so I consider it duplicate

  • @Danielomine all right, he learned to capture the event, cool, but he will manipulate the DOM and ready does not work after the onbeforeunload, because there will be a lock, what he wants is not this, he wants to display a form to subscribe to a newsletter, the solution in the other answer is only to ask if the guy really wants to leave the page, $("#modal_24").modal("show"); will never work on onbeforeunload, only if the user clicks on the page, but he asks here that it be if the user is leaving and this in the other answer does not explain. So the question here is broader than the other :)

  • exacerbado... Besides who should be clarifying should be the author of the question..

  • @Danielomine the question may be bad the way it was written, but from the code it is possible to see what he expected the script to do. However if it were to close should fall more as "typo" than duplicate. He asked to run script, that is to say a specific script and not prevent the closure itself. (ps. always use the @... because otherwise the message does not reach whom you want to send, only if the post is his)

Show 7 more comments

5 answers

9


Even if you use unload or beforeunload the form will never be displayed, this is because there is no way to prevent this, the use of unload is aimed at small actions, such as destroying cookies or sessionStorage, read this answer:

Jquery beforeunload is called when I click on link

By the time the event is run the page has already started to be "destroyed" (read about destruct and GUI in C/C++ or C# applications to understand how Guis work in operating systems).

Also understand that events unload and beforeunload are not only called in the close window, but any page that does it will run as the event is not called onCloseWindow (this event doesn’t even exist), it’s called onunload, translating unload would be like "download", ie the page loaded will be downloaded (or destroyed), each pagination, tab closure or window the event is triggered, ie using these events to call forms is a bad idea in every sense, besides very difficult to implement (or it would be impossible).

I recommend that you analyze what this form needs and see if this is really the best way.

Still if you really want to do it the way it is (which I personally find a terrible experience for the user) you should try using the beforeunload with return. Look at my answer:

Send message to browser

The code should look something like:

window.addEventListener('beforeunload', (event) => {
    // Cancel the event as stated by the standard.
    event.preventDefault();

    //Para customizar o texto, e é necessário para funcionar no Safari e Chrome, IE e Firefox anterior a versão 4
    event.returnValue = '';
});

This is the most that you will be able to prevent closure, if the user accepts, if not, infortunately has no way to force or control the user’s browser, the browser is his and if he wants to close everything has nothing to do, taking into account that it is very annoying some limitations that are placed on web pages that only make the user want to avoid certain websites.


How some websites manage to do this, such as facebook?

So I went to test, some people told me that on facebook a custom modal appeared when closing the window, but in fact this is a wrong impression of what happens, in fact when we click close tab or browser the screen that appears is this (if the text or comment field has a message not sent):

Evento beforeunload no facebook

That custom modal appears when we click on links inside the site where the script is running thanks to window.onpopstate, that is only occurs if click and links inside the site and do not close the page, see that here I filled the field "status" facebook and tried to click the link of another profile, the image that appeared to me was this:

Mensagem facebook window.onpopstate

So it’s actually a mistake and it’s impossible to customize the popup/modal of beforeunload, because if we could not control events without asking the user what would be basically you control the actions of the user (and this nobody wants to right).

  • 1

    And I’m glad I can’t control it. 'Cause if I go on a website of someone who did this to me, I’m never coming back

  • @Wallacemaxters Exactly this is one of the reasons, the other is that the event does not actually detect page closure, but rather downloading, of course when we close a page it downloads naturally, but it is a natural effect, as well as clicking on a link or entering a new address, you will need to download to load the new content ;)

  • I need to know how to take the option chosen as "Leave Page", in my case I have to do some checks and delete some cookies and make an ajax call before the final exit.

  • @franzisk that you want is FULLY troublesome, as I explained in https://answall.com/a/71023/3635, so the only efficient solution is to use a back-end timer to "eliminate" what has been IDLE for a long time. ps: if it were possible to do it efficiently when closing the window googleanalytics would use this, but it does not, so much so that I answered in detail a question on the same subject at https://answall.com/a/70316/3635

  • I understood @Guilhermenascimento, in this case I have a real problem to control this, since the authentication is simple, therefore it does not have a token with life time and such, and the same problem is that it is of vital importance to control the user output of the system, in this case the back-end is a Java Spring-Boot system. Thank you anyway.

1

I don’t know what version you’re using of jQuery, but the function unload() is deprecated since the version 1.8. You can use the function on() and wait for the event unload.

$(window).on('unload',function(){
  $("#modal_24").modal("show");
}); 

1

The listening Unload is already deprecated (was removed in version 3.0+ of Jquery), the most recommended method is the unbeforeunload that occurs when you press F5, CTRL+F5, click on a hyperlink or any element that with javascript redirects to another page, sending forms and etc.

Note that as @Guilherme Nascimento mentioned, in unbeforeunload/Unload you can not run any javascript, some as Alert("Hellow Wolrd") or calls that open windows window.open("http://minhaurl","minhaid","minhasconfigs"), redirects and etc are blocked by browsers. It has utility for example (as already mentioned): destroy cookies or sessionStorage.

In fact, there is no simple and unique way to listen to the "closing" (window being close) of a window but I went through a situation where I needed this functionality and followed the steps of the code below.

(The code below is a feature to clear the session of a logged in user after closing a window, it can also be adapted to other features that are allowed by browsers).

Follow the code tested and run on Chrome 67+ and Firefox 61+:

var wrapper = function () {

var deslogarUsuario = true;

 //Se o usuário está "focando" a janela, não há motivos para crer 
//que ele pretende fechar a mesma (oposto de blur)
$(window).on('focus', function () {
    deslogarUsuario = false;  
});

$(window).on('blur', function () {

    $(window).off('resize'); //evita listening múltiplos e desnecessários
    deslogarUsuario = true;
    //quando o usuário está minimizando a janela
    if (!document.hidden) {
        deslogarUsuario = false;
    }
    //quando o usuário está maximizando a janela
    $(window).on('resize', function (e) {
        deslogarUsuario = false;
    });

});

//Quando o usuário está deixando a página html, nos dá mais razões para 
//acreditar que ele pretende fechar a janela (com o mouse)
$('html').on('mouseleave', function () {
    deslogarUsuario = true;
});

//Quando o usuário está entrando na página, nos dá menos razões para 
//acreditar que ele pretenda fechar a janela (com o mouse)
$('html').on('mouseenter', function () {
    deslogarUsuario = false;
});

//Estas escutas são essenciais, pois F5 e CTRL+F5 também acionam o evento 
//onbeforeunload, você também pode tentar escutar por eventos como ALT+F4 
//mas este mesmo não terá o mesmo efeito, pois é primeiramente escutado pelo 
//navegador e efetuado a ação padrão (fechar)
$(document).on('keydown', function (e) {

    if (e.keyCode == 91 || e.keyCode == 18 && !blurOnPage) {
        deslogarUsuario = false;
    }

    if (e.keyCode == 116 || (e.ctrlKey && e.keyCode == 82)) {

        deslogarUsuario = false;
    }
});

//Evita que hiperlinks acionem a função no onbeforeunload
$(document).on("click", "a", function () {
    deslogarUsuario = false;
});

//Evita que botões acionem a função no onbeforeunload (útil para aqueles que 
//contiverem javascripts que redirecionam ou recarregam a página)
$(document).on("click", "button", function () {
    deslogarUsuario = false;

});

//Evita os submits de formulários
$(document).on("submit", "form", function () {
    deslogarUsuario = false;
});

//Evita os input[type="submit"] de formulários
$(document).on("click", "input[type=submit]", function () {
    deslogarUsuario = false;
});

//Função que pode ser utilizada ou adaptada para quando ocorrer fechamento 
//da janela
var derrubaUsuario = function () {
    $.ajax({
        url: '/MeuController/MinhaActionLogOut',
        async: false,
        data: {

        },
        error: function () {
        },
        success: function (data) {
        },
    });
};

window.onbeforeunload = function () {

    console.log('teste');
    if (deslogarUsuario) {
        derrubaUsuario();
    }
};

};

0

Depending on the version but I usually use the function unload()

$( window ).unload(function() {
      //Seu codigo
});

0

When the user tries to leave the page for any reason, the event beforeUnload is fired.

For example, when trying to submit a form, click on a link, close a window (tab) etc..

You can use the following code:

$(window).on("beforeunload", function() { 
    // seu código 
});

Source: How to capture the browser window close Event?

Browser other questions tagged

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