So the other day a client requested that when a visitor leaves any page on the site, they be greeted by an alert (such as ‘alert(‘this is your alert’);’) and if they click ‘Cancel’ they then go to an alternate ‘Exit Pop’ page that acts as a last ditch effort page to salvage a sale, or an opt-in, or dignity, what have you. Otherwise they just click ‘OK’ and go on their merry way in the opposite direction.
Usually I would just grab code from another page that I had done something similar on, but If you have ever dealt with old code before, You have either forgotten exactly what you needed to change in order for it to work ‘out of the box’ for your new situation, so you end up wasting about 10 minutes testing to get it right.
So I decided to streamline the process once and for all!
I had searched around the Googleverse for a similar simple script, but could not find an easy to use one that was contained in basically one easy to use file that did not include a kitchen sink of un-needed features.
I will try to explain my code. So here we go:
First, the page you want the action to happen on, in our case, is index.php
This is the only important bit of code needed on that page.
<script type="text/javascript" src="scripts/as_exitPop.js">
/***********************************************
|A|n|d|y|S|o|w|a|r|d|s|.|c|o|m|
------------------------------------------
* Easy Javascript/PHP Exit Pop up script @ AndySowards.com Developer's Blog (www.andysowards.com)
* This notice MUST stay intact for legal use
* Visit Andy Sowards at http://www.andysowards.com/ for full source code
***********************************************/
</script>
This is of course the code that includes the .js file(which will do all of our work) and will of course preserve my copyright information(which is creative commons, so basically you can do whatever you want with it, but please give me credit for it.). I usually place this code before the ending tag, but I have not tried it in the head code. Give me feedback if you try it that way!
Next is the actual .js file, which is called ‘as_exitPop.js’ and is located in the ’scripts’ folder:
//EDIT HERE ONLY
var ExitPopURL = ‘http://www.andysowards.com/dev/exitpop/exit.php’; //This is the URL where your ‘exit page’ is located.
/* NOTE: If you experience an error it is most likely due to the strict AJAX security, make sure that you are accessing the correct URL, for example, if you have http://domain.com in your browser, and http://www.domain.com in the ‘ExitPopURL’ then there will be a conflict. they must both match. .htaccess to ensure that your visitors are visiting www. is good practice here.*/
var AlertBox = “*****************************************************\n\nWait! Stop! Don’t Go!\n\nBefore leaving, please leave a comment on the \n\nscript post and share your suggestions.\n\nThanks for visiting AndySowards.com.\n\nAndy \n\n*****************************************************”;
// This is what the alert() pop up verbage says.
//DO NOT EDIT BELOW This LINE (Unless of course your Savvy!) ——————————
There is more to this .js file of course, but for the moment, this is all you really need to worry about.
First you see a var called ‘ExitPopURL’ and Hopefully is self explanitory to what it is. all you have to do is edit this in the .js file to be the url that points to your ‘exit pop’ page. Which means this is the page that will be seen if the user chooses to give you a ’second chance’.
Second, you see a variable called ‘AlertBox’, Again, hopefully self explanitory, but this is the variable that contains the text that will be seen in the javascript pop up alert box. You can change this to any verbage you would like.
Now for the next bit of code:
window.onload = function(){
// this is where we start our journey...
createExitPop();
}// end function onunload
What is happening here is that the createExitPop(); function(which is declared next) is running when the browser first loads the page. So basically when the page loads, your exit pop is hiding, like a tiger, waiting for someone to try and leave.
Next is your basic AJAX function, I will not explain this here because there are countless references and explanations of AJAX elsewhere:
function ajaxGET(divId, page, effect)
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch(e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
if(effect == ‘collapse’) { document.getElementById(divId).style.display=’none’; }
else { document.getElementById(divId).innerHTML=xmlHttp.responseText; }
}
}
xmlHttp.open(“GET”,page,true);
xmlHttp.send(null);
}
Next, Lets declare that createExitPop function:
function createExitPop()
{
var theBody = document.getElementsByTagName('body')[0];
var newdiv = document.createElement('div');
newdiv.setAttribute('id','ExitDiv');
theBody.setAttribute('id','body');
newdiv.setAttribute('style', 'width: 100%; height: 100%;');
// put div on page
theBody.appendChild(newdiv);
//add exit pop to page (contents are from your exit.php(or whatever you named it) page)
document.getElementById(‘ExitDiv’).value = ajaxGET(‘ExitDiv’, ExitPopURL);
// style exit pop to resemble its own page
document.getElementById(‘ExitDiv’).style.display = “none”;
document.getElementById(‘ExitDiv’).style.top = ‘0px’;
document.getElementById(‘ExitDiv’).style.left = ‘0px’;
document.getElementById(‘ExitDiv’).style.position = ‘relative’;
document.getElementById(‘ExitDiv’).style.backgroundColor = ‘#FFFFFF’;
}// end createExitPop
Here we are taking the body tag, assigning it to the ‘theBody’ variable and then setting an attribute to reference it, in this case we are setting the id of ‘body’.
Then we are creating a whole new div and calling the variable holding it ‘newdiv’. We then do the same thing with the new div that we did with the body tag, and add an attribute, an id of ‘ExitDiv’.
We also set some styles for our new div, in this case we set the width and height.
We then append the new div child to the body of the document. Once our new ‘ExitDiv’ is in the document, we can reference it using the DOM. We are using AJAX to inject our ‘exit.php’ contents into the div using the variable ‘ExitPopURL’ as the reference for content.
We then just add some styles and customize our ExitDiv.
We are almost done, Here is where the magic happens!
isExit = true;
function ExitPop(isExit) {
if(isExit != false) {
isExit=false;
isPop = true;
var bodyTag = document.getElementById? document.getElementsByTagName(“BODY”)[0] : document.body;
// add id=”body” so that it can be referenced.
bodyTag.setAttribute(“id”, “body”);
//replace body text with exit pop
bodyTag.innerHTML = document.getElementById(‘ExitDiv’).innerHTML;
return AlertBox;
} // end if
}// end function
window.onbeforeunload = function(){
// Lay down an exit pop!!
return ExitPop(isExit);
}// end function onunload
Here we set the variable ‘isExit’ to true. Why? Because if they try to do anything other than access an ‘isExit=false’ tagged link or form, then they are trying to leave the page! And we cant have that now can we? Of course not.
Inside the ExitPop function its parameter is the ‘isExit’ variable, it is evaluating whether or not it is true or false. If true, then the function replaces whatever is in the body tag with the inner HTML of the ExitDiv, which in turn makes the page have the content of your ‘exit.php’ page. An alert then pops up asking the user what they want to do, and you select the copy that goes in there using the ‘AlertBox’ variable.
Then, with the magic of the window.onbeforeunload method, before the window loads another page, it calls our ExitPop function and references the current state of the ‘isExit’ Variable.
Once the alert pops up, If they choose ‘OK’ they go. If they choose ‘Cancel’ they stay. Simple right?
Lastly, the only thing left is to make your ‘exit.php’ page look however you want! and the page will replace the with whatever is in your ‘exit.php’ file, and of course you can name the ‘exit.php’ file whatever you want.
One last note, if you have navigational links on your page that need to NOT trigger the exit pop functionality, simply add this attribute to the link ‘onClick=”isExit = false;”‘ or if you are using a form, then it would be ‘onSubmit=”isExit = false;”‘ and you should sneak past the security and on to the desired page
.
Hope you enjoy this and it helps save you time or make you money, and if you run into any trouble or have suggestions on making it better, let me know and I will implement the good ones!
For a Live Demo Example Click Here.
To download the original source code click here Easy Javascript/AJAX Exit Pop up script
by:Andy Sowards
Thx 4 Reading!

Awesome! Thank you so much. This is so close to what I was looking for.
Hey Andy,
Thank you for the script. It’s just what I’ve been looking for.
I do need to understand one additional thing since I’m a total newbie to this…
Would you give me an example of how to correctly add the onClick=”isExit = false attribute to some links on my sales page (also the ‘onSubmit=”isExit = false attribute to my form)?
Everything else works just great! Luv the script.
Thanks in advance.
Reggie
Hi, just wanted to say thanks: the script works perfectly; just what I was looking for. Just a thing though. I’ve been looking at the source code, and maybe I’ m missing something, but is there any way to change the confirm -or at least what I think is a standard javascript confirm()- that pops up into an alert?
Thanks again.
Hey andy, I just noticed your demo now works on IE8… Was script updated?
Need some help. Would like to popup a window instead of alert when the user leaves the page. I had something similar working using the onbeforeunload event handler and calling a hidden layer. I tried to integrate this into your code, however so that we could get the redirect and a popup and it shoots up the alert with [object] in the box. Any suggestions?
This worked awesome, I put it on my site and great!… except I use Firefox, which it works in, but not IE8 nor Opera10… ohh well looks like I be deleting this
Tried a few things but I am not gr8 with JS.
I did add an alert to tell people what to do, I see a lot of sites use this method:
bodyTag.innerHTML = document.getElementById(‘ExitDiv’).innerHTML;
// added
alert(‘Press “CANCEL” on the next box for your Special Offer!!!’);
// end added
return AlertBox;
Hey Andy, any luck with getting this working on new browsers?
Hi Andy!
I was trying to install the script in my page but to no avail.. it didn’t work out..
first of all, do the need to be in PHP or can it be in HTML also with the exit page.. I try to paste the code into HTML page.
Hope you can answer me because i badly need this one.
Thank you and more power.
But this exit popup triggers out when you refresh the page.. is it possible to prevent this..
Hi Andy,
[Please ignore my earlier comment. I failed to insert the code there)
It's a cool script that you have got. But I have a rather unusual problem. I have an Flash audio player embeded in the web page. When i tried to play the audio player the script is getting active. It's a embeded "object" thing and I am clueless where to put this code - onClick="isExit = false;" so that the popup doesn't become active. I think the same problem could occer if somebody has a youtube Video embeded in the webpage and tries to play it.
Please suggest a solution to this problem.
The code is as follows -
[CODE]
[/CODE]
sorry script code did not paste in but can be seen here near top of page:
andynock dot com /new
Thanks
Hi Andy
Is it possibe to stop the exit page appearing when a opt-in form is submitted such as:
//GetResponse popup code
Thanks in advance.
Andy
Hi Andy,
I was wondering if I can swap the function of OK and CANCEL button when pop-up window appears.
So, when users click OK then he/she will stay on the exit.php and when CANCEL button clicked, he/she leaves forever.
can we do that?
Great script really helpful in getting my head around this. I have some questions though:
1. Do we have to call the alert box? The formatting looks so plain. Could we replace that with a fully formatted layer?
2. is it possible to change the buttons at the bottom to different things (Cancel to ‘Stay on this page’ or Ok to ‘Not interested’.
Really cool script. Is it possible to have the exit page defined an external link and to have the OK and Cancel functions reversed?
Here’s the example:
You’re about to leave the site and then you are prompted with a prompt that says, “Would you like to visit site A on your way out?” and then if they click ‘OK’ it would take them to the URL defined as the exit page.
I was hoping your script would be easily modified to work that way.
Would love to hear your feedback/suggestions.
Thanks buddy!
Dave
Hello!, great stuff, just a question, is there a way to load the popup ONLY on domain exit? and not on page exit?????????
is it possible to change the buttons at the bottom to different things (Cancel to ‘Stay on this page’ or Ok to ‘Not interested’. If so is it possible to modify the line just above the functions?
Thanks.
Can you alter the code so that instead of the exit changing everything between the body tags, it changes everything inside of div id=”X”?
OK, got it all working so far. Just a couple more questions.
1. How could I change the body style class from the original page to suit that of the exit page?
2. Also, is it possible to change the page title?
The second question is not as important but it would be great if you could provide a solution.
Many thanks again Andy. I look forward to your response!
Loi
OK, got the color working.
Now how can I change the body background image?
Thank you very much for your help Andy, it is greatly appreciated.
Andy,
I cannot get it to work.
Do I need to add anything to my body tags?
Sorry about the previous post.
My question was do I need to insert anything into my body tag?
At the moment I have body bgcolor=#cccccc
thanks
Thanks for the quick reply Andy. I inserted the code but still cannot get it to work?
Do I need to insert any code into my tag?
At the moment I have
Thanks again!
Hey Andy,
How do you change the background color when the exit popup shows? I want to use a different color for the exit.php file.
Please respond. Thank you.
Hey Andy,
Thanks for the tip, but unfortunately it didn’t work. Its not popping on anything now.
Great information Andy.
Just a couple of questions:
1. Is it possible to change the body style, background color or image within the exit page that is displayed?
2. Also, could you change the title meta tags as well?
Thanks a bunch!
Hey Andy. Great script, but I wanted to know if I can do the opposite. Have it run if only certain buttons are selected.
I tried messing with the isExit section, but to no avail. Any pointers?
Thanks.
HI
I try to use this with iframe, not a div. But it not work.
Why iframe? Because I want run JavaScript on pop-up page.
I do this:
replace:
var newdiv = document.createElement(‘div’);
to
var newdiv = document.createElement(‘iframe’);
and
document.getElementById(‘ExitDiv’).value = ajaxGET(‘ExitDiv’, ExitPopURL);
to
document.getElementById(‘ExitDiv’).src = ajaxGET(‘ExitDiv’, ExitPopURL);
but when pop-up go , I saw only plain text of page NOT FORMATED HTML.
what do you think?
P.S. sorry for my english
Just another thought that came up. How Google-friendy do you think a popup of this nature is? Perhaps it’s a type of code best placed and used sparingly on very few pages, instead of on a whole website?
So I’ve run into another problem with your script! When you refresh the page, the script activates, thinking you’re leaving (instead of just refreshing the current page). While I’m not sure how many users are going to be refreshing a page, this can be a problem!
Okay never mind, I realized my mistake. No breaks in the message for the javascript popup.
I’ve tried implementing this on my website, but it doesn’t seem to want to cooperate with me. Everything is in place but when I navigate away from the page, the popup does not appear. Any idea what’s wrong?
Thank you so much Andy! Your script just saved me 67 dollars. I would have bought Exit Splash is I didn’t find your website. There is one thing that you should know. The instructions you provided are very hard to follow. Also, please move the source code link to the top of the page. I almost couldn’t get the code to work because of a bad src link. The link you provided didn’t work. I had to replace it with the real file location. You should include this detail in the instructions. Sorry, if I seem critical. You’re a genius! Your graphics are radical!