Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript window close event rather than unload event for all browsers

Tags:

javascript

I want to alert a user while the user tries to close the browser with out siginingoff or without saving some settings.

I am ding unload option in another page to alert unload data, but how can i alert a user on window.close(its not taking)

window.onbeforeunload = confirmExit;
function confirmExit(){
    if(readCookie("onlineVD") == "playing" && Confirm_Delete=="0")
    {
        return "You are leaving a video which is in play mode.Are you sure want to exit this page?";
    }
    else{
        Confirm_Delete="0";
    }
}

I want window.close for on tab close and on window close in all browsers.

Please find me a solution

like image 914
Elamurugan Avatar asked Jan 04 '10 07:01

Elamurugan


People also ask

What is the difference between Onbeforeunload and Beforeunload?

One significant difference (other than cancelability) between the onbeforeunload and onunload is that the former is triggered for download links and the latter is not.

Can JavaScript close a window?

JavaScript provides an in-built function named close() to close the browser window that is opened by using window.

Can we capture browser close event?

A tab or window closing in a browser can be detected by using the beforeunload event. This can be used to alert the user in case some data is unsaved on the page, or the user has mistakenly navigated away from the current page by closing the tab or the browser.


2 Answers

The event code you have already seems to work when I test it. You just need to return false to stop the browser from closing. The user will be asked if they're sure they want to navigate away from the page.

I'm using this shortened version of your code:

window.onbeforeunload = confirmExit;
function confirmExit(){
    alert("confirm exit is being called");
    return false;
}
like image 184
Richard Garside Avatar answered Oct 20 '22 21:10

Richard Garside


The Mozilla documentation indicates that you should set the event.returnValue instead of simply returning a string:

window.onbeforeunload = confirmExit;
function confirmExit(e){
    if(readCookie("onlineVD") == "playing" && Confirm_Delete=="0")
    {
        var msg = "You are leaving a video which is in play mode.Are you sure want to exit this page?";
        if (e) {
            e.returnValue = msg;
        }

        return msg;
    }
    else{
        Confirm_Delete="0";
    }
}
like image 30
Rob Van Dam Avatar answered Oct 20 '22 20:10

Rob Van Dam