开发者

How to change css visibly before returning something on "window.onbeforeunload"

开发者 https://www.devze.com 2023-04-01 10:43 出处:网络
I would like to ask a question about window.onbeforeunload. I consider making a coveri开发者_Python百科ng-element appear before confirming whether to unload or not.

I would like to ask a question about window.onbeforeunload.

I consider making a coveri开发者_Python百科ng-element appear before confirming whether to unload or not. But the following code seems not to work fine. The dom element 'COVERALL' appears just after confirming unloading.

window.onbeforeunload = function(event){

    $( COVERALL )
        .css('zIndex', 1000000)
        .fadeTo(1000, 1.0);

    ~~~~
    ~~~~
    some time-consuming tasks here
    ~~~~
    ~~~~

    return event.returnValue = "are you sure?";
}


The correct way to do this is using an event listener to capture the event object and then prevent the default action which is to leave.

window.addEventListener('beforeunload',
    function(e)
    {
        if (!confirm('Are you sure that you want to leave?'))
            e.preventDefault();
    }, 1);

Its implementation may vary between browsers though. In my Fiefox 6, it asks again to confirm once the e.preventDefault(); instruction is reached, as a security measure implemented by Mozilla.


August 1st:

Today I have tried, and, in Chromium browser, if you prevent default action without asking user for confirmation such as with a confirm box, the page will close anyways.

I did some research today about this, and I have found that it is apparently impossible to trigger a page close event from Javascript, so using a custom HTML made confirm box for this would be out. I tried creating custom events, dispatching them to various window elements and even inspecting and copying browser made events. (All this on Firefox, in Chromium I did not check because, well, no support in Firefox means not to ever rely on something like that)

But good news for you, I have found that if you quickly set up an XMLHttpRequest and send the information you want to save before leaving, the data sending will finish in background even if the page has been closed.

I have successfully been able to achieve that for both browsers with the following code.

window.addEventListener('beforeunload',
function(e)
{
    var fd = new FormData();
    fd.append('html', document.body.innerHTML);
    var xhr = new XMLHttpRequest;
    xhr.open('POST', './dataRetriever.php');
    xhr.send(fd);
    // uncomment these if you want confirmation for all browsers
    // because this code will not ask for confirmation in others
    // than Mozilla powered ones.
    //if (!confirm('Leave?'))
    //  e.preventDefault();
}
, 1);

With that one, I send all the body innerHTML to my dataRetriever.php script so tell me how it goes and if it works for you as expected.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号