Run script js when trying to close the window

6

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 I try to close the window open this form and only close the window if I click on the submit or close the popup

I tried this over and closed the window:

global $xTema;
$xTema->addJSOnReady('
$(window).unload(function(){
$("#modal_24").modal("show");
});
');
    
asked by anonymous 07.01.2016 / 21:47

5 answers

9
  • First the unload event does not exist as has been said by some

  • Second, even if you use unonload or beforeunonload the form will never be displayed, this is because you can not prevent this, the use of unonload is aimed at small actions, such as destroying cookies or sessionStorage , read this answer:

    At the time the event runs the page has already begun 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 unonload and beforeunonload are not only called in the close window, but any page that does it will be executed, because the event is not called onCloseWindow (this event neither exists) is called onunload , translating unload would be like "unload", that is, the page loads will be downloaded (or destroyed), every pagination, window closure or event is triggered, ie use these events to call forms is a bad idea in every way, and very difficult to implement (or impossible).

    I recommend that you review the need for this form and see if this is really the best way.

    Even if you really want to do it the way you do (which I personally find a bad experience for the user) you should try to use beforeunonload with return . Here's my answer:

    The code should look something like:

    window.onbeforeunload = function(e)
    {
        setTimeout(function() {
           $("#modal_24").modal("show");
        }, 10);
    
        var msg = "Antes de sair gostaria de responder a nossa pesquisa?";
        e = e || window.event;
    
        // Pro IE e Firefox anterior a versão 4
        if (e) {
            e.returnValue = msg;
        }
    
        // Para Safari e Chrome
        return msg;
    }
    

    This is the maximum you can prevent from closing, if the user accepts, if not, in thankfully there is no way to force or control the user's browser, the browser is his and if he want to close everything has nothing to do, taking into consideration that it is very annoying some limitations that are placed on web pages that only make the user want to avoid certain sites.

How can some website do this, such as facebook?

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

Thiscustommodalappearswhenweclickonlinkswithinthesitewherethescriptisrunningthankstowindow.onpopstate,ieitonlyoccursifyouclickandlinkswithinthesiteandnotclosethepage,seethatIfilledthefieldhere"status" of facebook and I tried to click on the link of another profile, the image that appeared to me was this:

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

    
14.02.2016 / 04:21
2

Listening unload is already < strong"> unbeforeunload that occurs when you press F5, CTRL + F5, click a hyperlink or any element that with javascript redirects to another page, forms submission and etc.

Important to remember that as @Guilherme Nascimento mentioned, that in unbeforeunload / unload you can not run any javascript, some like alert ("Hellow Wolrd") or calls that open window.open (" link ", "myid", "myconfigs"), redirects and etc are blocked by browsers. It has utility for eg (as already mentioned): destroy cookies or sessionStorage.

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

(The code below is a feature for clearing the session of a user logged in after closing a window, it can also be adapted to other functionality that is 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();
    }
};

};

    
27.07.2018 / 23:32
1

I do not know which version you are using from jQuery, but the unload() > is deprecated since 1.8 version . You can use the on() function and wait for the event unload .

$(window).on('unload',function(){
  $("#modal_24").modal("show");
}); 
    
07.01.2016 / 23:01
1

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

$( window ).unload(function() {
      //Seu codigo
});
    
08.01.2016 / 09:48
1

When the user attempts to exit the page for any reason, the beforeUnload event is fired.

For example, when attempting to submit a form , clicking a link , closing 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?

    
15.02.2016 / 14:10