3

I realize this is likely a duplicate, but I've been googling/SOing for a day now and I can't find a satisfactory answer. If there is an answer already on SO, please send me there.

I have a client that insists on having an exit message popup confirming they want to exit the site, just like Gmail does. (I've already tried arguing against it. He is immovable, so no comments about how that is bad practice please.)

I've found this code:

<script>
    window.onbeforeunload = function() {
        return 'Are you sure you want to exit?';
    }
<script>

But it runs no matter what I do - reloading the page, clicking on the nav, etc.

I just want the message to show up when the user closes the tab/browser. I suspect it's something simple I'm missing but I'm not a Javascript expert.

Any help would be greatly appreciated.

Thanks

EDIT

Here's what is working pretty good. Thanks to all!

var isLeavingSite = true;

//This would be called on each link/button click that navigates
$('a, input[type="submit"]').click(function(){
    isLeavingSite = false;
});

window.onbeforeunload = function() {
    if(isLeavingSite)
    return 'Are you sure you want to exit?';
}
4

3 回答 3

1

Though it could be a fair amount of work (depending on how your site is written), you could do something like this (pseudo-code):

var isLeavingSite = true;

//This would be called on each link/button click that navigates
function GlobalLinkHandler()
{
    isLeavingSite = false;
}

window.onbeforeunload = function() {
    if(isLeavingSite)
    return 'Are you sure you want to exit?';
}

If you're using jQuery, you can use the code below to flip the isLeavingSite flag:

$('a, input[type="submit"]').click(function(){ isLeavingSite = false; });
于 2011-11-18T16:51:01.983 回答
1

What'll have to do is make use a variable that you set if any link is clicked on the site, then inside the onbeforeunload event check if that variable is set meaning they clicked a link or not set meaning they're closing the tab.

You can also use that variable to simple set the href of the link; that will allow you to then check what link they clicked on inside the onbeforeunload event and allow you to check if they're clicking on a link to go to another page on your site or clicking on an external link to another site.

于 2011-11-18T16:51:56.650 回答
0

If your using jQuery try this Confirm before exit

于 2011-11-18T16:50:20.430 回答