INTRODUCTION/DISCLAIMER: Yes, I know this is bad. Yes, I've let the client know what I think of this. NO, I would never do this on my own website. I loathe this concept. However, sometimes you have to do what you have to do to let the client see for himself or herself how the user experience is compromised, on a test version of his or her website.
There are also legitimate cases where such as feature is useful, such as to prevent loss of data. Stack Overflow uses the Exit Popup to prompt you to save your data if you accidentally navigate to another page while you're posting a question or answer.
With that said, let's move on.
The Problem Description:
I have a JavaScript function I'm running, located on Snipplr - Confirm Leaving Your Site Onbeforeunload.
window.onload = function(){
var allowUnload = true;
window.onbeforeunload = function(e){
//allowUnload will allow us to see if user recently clicked something if so we wont allow the beforeunload.
if(allowUnload){
//message to be returned to the popup box.
var message = 'Are you sure you want to leave this page message',
e = e||window.event;
if(e)
e.returnValue=message; // IE
return message; // Safari
}
};
// We need this to allow us to see if user has clicked anywhere if user has clicked we wont allow beforeunload to run.
document.getElementsByTagName('body')[0].onclick = function(){
allowUnload = false;
//setTimeout so we can reset allowUnload incase user didn't leave the page but randomly clicked.
setTimeout(function(){ allowUnload = true; },100);
};
};
The code snippet prevents the Exit Popup from showing if a user clicks a hyperlink on the page. The Exit Popup shows itself for F5 refresh, as well as when the user leaves the site. This is the desired behavior, with a single exception.
If I click a button that contains an onclick
event that replaces parent.location
with the new link, the Exit Popup fires:
<input type="button" onclick="parent.location = '/test.html';" />
What do I need to add to the code snippet to prevent this button click from launching the Exit Popup?
The Constraints Are As Follows:
- I don't have access to the site, just a JavaScript file, hosted on my domain, used to deploy a proactive chat feature.
- I cannot modify the
onclick
event obtrusively (by editing the attribute directly). - I could modify the
onclick
event dynamically, but it won't be documented on their end and could cause confusion when/if they later decide to change theonclick
attribute. - I would prefer to intercept the
onclick
attribute and add to it, so if it's changed, the changes will be recognized. - This must work in IE7+, Firefox, Chrome.
- As much as I love and promote jQuery and will be the first to make such a suggestion, I cannot use it here, unfortunately.