How can I detect exit intent on a mobile browser? - javascript

I'm working on a solution to detect exit intent on safari mobile. (or any mobile browser for that matter)
On desktop I can track curser movement and when the user breaks the plane of the webpage I can initiate a pop up. See http://www.quicksprout.com/about/ as an example. Move your curser up to the back button on the browser and as soon as your curser breaks the webpage a pop up will appear. How can I solve this in a mobile environment?
Is there any way to detect when someone clicks the Safari address bar and before the favorites screen appears I can launch a pop up then?
Thank you in advance for the help.

I know this is over a year later, but maybe my answer might still help someone in the future.
On some of my sites, I found that mobile exit intent often consists of a slight upward scroll before the user hits their back button. For example, users often scroll down the page quite a bit while consuming content, but when they're ready to leave they might scroll upwards slightly (say 5-10% of the page height), and then they'll go hit the back button or close the tab.
I use that knowledge to pop up a newsletter sign up form on some of my content sites, and it actually works well without annoying the user. So if I ever detect that a user scrolled down at least 50% of my page, then back up by at least 5%, I hit them with a popup since I think they liked my content but are ready to exit the page. I wrote some simple Javascript that actually lets me detect such behavior at https://github.com/shahzam/DialogTriggerJS
Not sure if that's the exact answer you're looking for, but hope that helps a bit!

I just came back from a long trip around the web with the same goal in mind however as of now - you really are not able to detect if a user clicks on the address.
However I found out that you can look for patterns that users are making before they are ready to leave your website or abandon shopping cart. Here is show how we solved this and made mobile exit intent work on all mobile devices in case if the user quickly scrolls back up the page since that can be a sign that shows that the user has lost interest in our content and might want to leave.
Detecting if the user is on a mobile device.
This part is rather simple - we use Javascript to check if the event is "touchstart" and if so, we are adding a class to our body tag:
jQuery(document).on('touchstart', function(){
$(body).addClass('on-mobile-device');
});
Detecting the scroll direction, scroll speed and displaying Exit Intent popup:
function myScrollSpeedFunction(){
if( jQuery('body').hasClass('on-mobile-device') ){
if(my_scroll() < -200){
//Your code here to display Exit Intent popup
console.log('Must show mobile Exit Intent popup')
}
}
}
var my_scroll = (function(){ //Function that checks the speed of scrolling
var last_position, new_position, timer, delta, delay = 50;
function clear() {
last_position = null;
delta = 0;
}
clear();
return function(){
new_position = window.scrollY;
if ( last_position != null ){
delta = new_position - last_position;
}
last_position = new_position;
clearTimeout(timer);
timer = setTimeout(clear, delay);
return delta;
};
})();
jQuery(document).on('scroll', myScrollSpeedFunction );
This is basically it. This way you are not interrupting the user's flow since the user has already finished looking at the content and going up very quickly and we can present him with a message.
What we have done ourselves besides this code is to make sure our Exit Intent popup is displayed only in case if the user has got a product in his shopping cart since we are suggesting to save the users shopping cart and remind about his abandoned cart via email.
You can test it out on our product page here: https://www.cartbounty.com, just remember to add a product to the shopping cart before you test drive it on your mobile device.

At least on mobile safari, you're looking for the window.onpagehide function. This event will fire immediately after the page is hidden.
Here is a snippet showing this code in action:
<!DOCTYPE html>
<html>
<head>
<script> window.onpagehide = function(e) { alert("Don't go! I'm lonely!"); }</script>
</head>
<body>
</body>
</html>
Unfortunately, it looks like if you want an event to fire before the page is hidden, you're out of luck, because mobile Safari halts execution of everything on the page when the user clicks on the address bar. This means that you cannot, for example, monitor the page height to see if the user is typing on the keyboard (as they would be if they clicked the address bar).

Some simple code to detect exit intent on a mobile device.
It detects exit intent through the speed of the user's upwards scroll.
It delays 10 seconds before enabling. You probably should make it about 30 seconds if you only want to show your exit intent popup to people who are really interested in your content.
setTimeout(() => {
document.addEventListener("scroll", scrollSpeed);
}, 10000);
scrollSpeed = () => {
lastPosition = window.scrollY;
setTimeout(() => {
newPosition = window.scrollY;
}, 100);
currentSpeed = newPosition - lastPosition;
console.log(currentSpeed);
if (currentSpeed > 160) {
console.log("Exit intent popup triggered");
document.removeEventListener("scroll", scrollSpeed);
}
};

Related

jquery scrollTop() not working in chrome

I have already checked a few questions in SO and over the Internet about this issue.
My problem statement is following: I have a gaming site which refreshes based on user action, and when it refreshes I want the user to be scrolled to a location that was decided before reload based on user action.
How I do it is, before reloading the page I store the calculated offset to localStorage.
window.onbeforeunload = function(){
var scrollTo = calculateNextLoadPosition();
//below function validates & calls localStorage.setItem(name,value);
storeLocalData("scrollTo",scrollTo);
console.log("Stored scrollPosition "+ scrollTo);
};
When page refreshes, I read this localStorage value and scroll page to that offset.
$(function() {
//retrieve the stored scroll offset as an integer
var scrollTo = parseInt(getLocalData("scrollTo"));
$('html,body').scrollTop(scrollTo);
console.log("Scrolled to "+scrollTo);
//also tried..
//$(window).scrollTop(scrollTo);
//$(document).scrollTop(scrollTo);
}
When I reload browser with this script, the calculated offset is always correct, the value in browser localstorage is also correct when I examine it using developer tools. But the browser never scrolls to that location even though in console it writes that it has scrolled to that position. It just stays at the top.
Additional info:
I do not have overflow-x or overflow-y anywhere in the HTML
It works like aa charm in Firefox
It is driving me nuts and I am about to chew on my hat in frustration!
Any pointers on what is going wrong is greatly appreciated!

How can I tell if iPhone is returning from background in javascript?

I know that the iPhone stops javascript from running when an app is sent to the background (ie pressing the home button while the app is running), but I would like to be able to detect if this has happened when the javascript starts up again when the app is reactivated.
One solution I've been trying is to have an iterator constantly running to "check in" and then running a check against that to tell if the app has gone to background.
var lastCheckinTime = new Date().getTime();
function checkin(){
lastCheckinTime = new Date().getTime();
}
setIterator( checkin, 1000 );
// Later, some code that needs to know if iphone went to background
var now = new Date().getTime();
if( (now - lastCheckinTime) > 1100 ) {
// run sent to background code
Is there a better way to do this? The problem I've found with this method is that it doesn't work if the user quickly closes and reopens the app, but I haven't figured out a better way of detecting this yet.
You can use the 'pageshow' event. Visit this page on your phone, http://jsfiddle.net/vbuDh/
window.addEventListener('pageshow', function(ev){
alert('dasd');
},false);​
This will fire anytime the tab gains focus, or mobile Safari is reactivated on this page.

In JavaScript, is there a start scroll event for the iPhone browser?

I would like to detect when a user starts to scroll a webpage in the iPhone web browser. Is this possible?
Use an onscroll event as usual and delete it when the user scrolled for the first time.
window.onscroll = function() {
alert("I saw that!");
window.onscroll = null;
}

Frame Busting buster not completely working for IE

I've been working on a Frame busting buster (what's in a name, hehe), which kept my users on my page and open a new window with the target URL. I'm using a Lightbox script to display iframes, this is what I'm doing:
1) Added an event for all .lightbox clicks, f.e:
$('.lightbox').live("click", function(e) {
e.preventDefault();
$('#redirectURL').val($(this).attr('href'));
$(this).lightbox();
}
2) Added a frame busting buster:
<script type="text/javascript">
var prevent_bust = 0
window.onbeforeunload = function() { prevent_bust++ }
setInterval(function() {
if (prevent_bust > 0) {
prevent_bust -= 2
window.top.location = 'http://server-which-responds-with-204.com'
}
}, 1)
</script>
3) Modified the frame busting buster code to fit my needs, which are:
detect if an iframe wants to change the window.top.location
if so, prevent this from happening using the 204 server respond
open a new page: window.open( $('#redirectURL', '_blank' );
close lightbox: $('.jquery-lightbox-button-close').click();
So far, this is what I've come up with:
var prevent_bust = 0
window.onbeforeunload = function() { prevent_bust++ }
setInterval(function() {
if (prevent_bust > 0) {
prevent_bust -= 2;
redirectURL = $('#redirectURL').val();
if(redirectURL != "") {
window.top.location = 'http://www.****.com/ajax/nocontent.php';
window.open(redirectURL, "_blank");
$('.jquery-lightbox-button-close').click();
$('#redirectURL').val('');
} else {
window.top.location = 'http://www.****.com/ajax/nocontent.php';
}
}
}, 1);
// EDIT: Before I forget, 'nocontent.php' is a file that returns a 204 header
For Firefox it acts as I programmed it, if there's a change detected in the window.top.location it opens a new frame/page and prevents the iframe from reloading the top location and to round it up, it closes the jQuery lightbox.
Safari/Chrome act similar, they open a new browser screen (not sure if theres an option to say target="_newtab" or something?). Only bad thing is they do not really display a message of the popup is blocked, but I can work around that by displaying a popup balloon on my website with a link to the page.
Internet Explorer is, what a shocker, the only black sheep left.. IE does not open a new popup, nor blocks the window.top.location reset by the iFrame and simply continues refreshing the complete page to the '#targetURL'. It does the same with the default busting code.. so it's not because of some of my edits.
Anyone who is able to spot a mistake in my code?
Also, I would need a little modification that sees if the request has been made by an iframe or by the user itself, because now there is really NO option for a user to leave my page by changing the address in the toolbar or by clicking a link, which is not really needed LOL.
Thanks in advance.
PENDO, I tried to simulate the whole process you described, ligthbox-jquery, javascript their own codes and controls opening pages via lightbox. I could not simulate at all, and as time is running out I'm sending a suggestion to broaden the range of possibilities and solutions.
I suggest replacing the redirect page:
...
redirectUrl = $ ('# redirectUrl'). val ();
...
window.top.location = 'http://www .****. with / ajax / nocontent.php';
window.open (redirectUrl, "_blank");
Replaced with a DIV container that simulates a page, using ajax calls and taking the content and overwritten the contents of the DIV.
...
$.post(redirectoURL /* or desired URL */, function(data) {
$('DIV.simulateContent').html(data);
});
...
or
...
$('DIV.simulateContent').load(redirectoURL);
...
This approach also avoids the problem of preventing the user from even leaving your page using the address bar (as you yourself mentioned).
Sorry, let me give you a complete solution, but time prevented me.
PENDO, a little more work on alternatives to the problem, I found a customizable jQuery lightbox plugin for working with custom windows yet (iframe, html, inline ajax etc.). Maybe it will help. The following link:
http://jacklmoore.com/colorbox/
If you don't need javascript running in your iframe in IE, you can set the iframe security attribute :
<iframe security="restricted" src="http://domain.com" />
http://msdn.microsoft.com/en-us/library/ms534622(v=VS.85).aspx

Use Javascript to get selected text in Mobile Safari

So I'm working on a bookmarklet where it would be ideal for me to grab the content selected by the user using the "loop". Both window.getSelection and document.getSelection are functions that I can call, however, they always return an empty string.
I believe the problem is that when you tap on the bookmark icon in Mobile Safari, the selection is released. For example, if you select some text, tap the "+", bookmark or other tab, the selection is unselected even if you cancel.
Any thoughts on if it is possible to get at this data at all? Or is this pretty much impossible?
I think you would have to have the bookmarklet insert some content into the page that would operate on the selection. You might add a button to the top or bottom of the page, and when clicked it would act on the current selection. It could then clean up the added content or leave it there.
The contents of the "loop" are not exposed to javascript in the mobile browser, period. So this is impossible (I am assuming that you are working in the full browser, not in the browser window created when you launch a "saved to home page" icon)
I have a fairly simple idea.
var latestSelection = "";
while (true)
{
var tmp;
if ((tmp = document.getSelection()) != "")
latestSelection = tmp;
}
This way you would always have the latest selection in the latestSelection variable. Of course it would be expensive to have a loop run like this all the time. So you will probably want to play around with listeners or at least timers.
Hope this helps.
Update:
Don't use the above code as is.
Here is how you would write the same thing in objective-c:
- (void) updateSelection
{
NSString * tmp = [webView stringByEvaluatingJavaScriptFromString:#"document.getSelection()"];
if (![tmp isEqualToString:#""])
latestSelection = tmp;
}
You could have a timer execute updateSelection every x time units. If you find some good notification that let's you know that the user has interacted with the webview, you could use that to update latestSelection.

Categories