Rich-text Reply

Detect that user is going to leave the page

miguelm 03-09-16

Detect that user is going to leave the page

Hi,

 

I would like to detect when the user is going to leave the page, in order to show him a pop-up. I see this in many pages, but I don't know which is the best way to detect this. Anyone knows how to do it?

 

Thank you

Level 2

tobyurff 03-14-16
 

Re: Detect that user is going to leave the page

Hi Miguel,

Detecting if a visitor wants to leave your site without disrupting their flow if they don't is quite difficult to accomplish, so it's probably best to use a exit intent tool for such overlays.

You can test the influence such a tool has by leaving the Original in your experiment as is and adding the Javascript file of your exit intent tool only in the Variation Javascript. Here's a code sample of how to achieve that.

 

Hope this helps,

Toby

Optimizely
miguelm 03-14-16
 

Re: Detect that user is going to leave the page

Thank you for your anwer Toby. I'm going to try the open source solution https://github.com/carlsednaoui/ouibounce that you mentioned on your post.

 

 

Level 2
miguelm 03-14-16
 

Re: Detect that user is going to leave the page

Hi Toby,

 

How can I check that the external JS is loaded correct? In order to load the external javascript I added the following code in the variation code:

var loadScript = function(location, callback){
   var fileRef = document.createElement('script');
   fileRef.setAttribute('type','text/javascript');

   if (callback) {
     if (fileRef.readyState) {  // IE
       fileRef.onreadystatechange = function() {
         if (fileRef.readyState == 'loaded' || fileRef.readyState == 'complete') {
           fileRef.onreadystatechange = null;
           callback();
         }
       };
     } else {  // Non-IE
       fileRef.onload = function(){
         callback();
       };
     }
   }

   fileRef.setAttribute('src', location);
   document.head.appendChild(fileRef);
 };

 loadScript('https://cdnjs.cloudflare.com/ajax/libs/ouibounce/0.0.11/ouibounce.js', function() {
   
 });

However, whe I call the function which is described on the extenal JS, I get the error "ouibounce is not defined",so I suspect that is not loading properly the JS

Level 2
tobyurff 03-17-16
 

Re: Detect that user is going to leave the page

Hi Miguel,

 

 

 

 

You'll need to make sure the file has finished downloading before you try to use it. Luckily, there is a callback function that fires as soon as the download is finished, so you need to move all your code into this callback function, like so:

 

loadScript('https://cdnjs.cloudflare.com/ajax/libs/ouibounce/0.0.11/ouibounce.js', function() {
   // All code that depends on the Javascript downloaded goes here.
});

Hope this helps!

 

Thanks,

Toby

Optimizely