I am working on a site that provides the user with quotes and reservations for rental equipment. If the user gets more than a few steps into the processes and chooses to close the browser or navigate away before finishing then the client would like to offer then a special deal. The client would like to prevent the window from closing and ask them for their phone number so they can call them with a better rate if one becomes available.
I can prevent the window from closing and the prevent the browser from navigating away. When this happens, a div is displayed with a little for for the user to submit and an option to go ahead and close the window. This all works fine. The problem is that if the user refreshes the page or hits the back or forward buttons then the action is being blocked just as if the user was closing the browser. But I don't care if they go forward or back or refresh the page because that means they are still in the reservation process. Unfortunately, I cannot distinguish between the two types of events.
I am attaching a function to the onbeforeunload event to trigger the message to the user. The site I am working on is an ASP.NET site, if that is helpful to anyone.
Here is the code I am using. The elements divSecondClose and divThankYou are both set to display:none when the page first loads. <%=DisplayThankYou%> is set to 'true' after the form has been submitted so that a thank you message appears.
var showSecondCloseOnExit = true;
var displayThankyou = '<%=DisplayThankYou %>';
if (displayThankyou == true)
{
var divSecondClose = document.getElementById('divSecondClose');
divSecondClose.style.display = '';
var divThankYou = document.getElementById('divThankYou');
divThankYou.style.display = '';
showSecondCloseOnExit = false;
}
else
{
addListener(window, 'beforeunload', CloseWindowEvent, false);
var allLinks = document.getElementsByTagName('a');
for (var linkIndex = 0; linkIndex < allLinks.length; linkIndex++)
{
addListener(allLinks[linkIndex], 'click', function(){showSecondCloseOnExit = false;}, false);
}
}
function CloseWindowEvent(e) {
if(!e) e = window.event;
if (showSecondCloseOnExit)
{
var divSecondClose = document.getElementById('divSecondClose');
divSecondClose.style.display = '';
showSecondCloseOnExit = false;
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = 'RATE CHANGE NOTIFICATION\nWould you take a moment before you leave to help us serve you better?';
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
}
}