7

I have a html5 mobile app where everything exists on a single page and I use history.back/popstate/etc to change the contents of the page (via jQuery Mobile). I'm using Google Analytics to track various events, and on one page I track if the user exits via a particular button:

$('#my-back-button').bind('tap', function() {
    _gaq.push(['_trackEvent', 'mycategory', 'myaction']);
    history.back();
    return false;
});

In the android 2.2 browser history.back() is called but onpopstate is not fired and the page isn't changed. If I put window.onpopstate = function() { alert("!"); }; just before the history.back(), I see no alert.

If I reverse the two lines (history.back() first, then _gaq.push), it seems to work, but I can't rely on this kind of ordering throughout my code.

No exceptions are being thrown. It works fine in iOS and desktop Chrome.

Any ideas why history.back() doesn't work after a google analytics call?

DurhamG
  • 222
  • 2
  • 9
  • I am having the exact same issue. I don't suppose you've come up with a solution or workaround since first posting this months ago, have you? – Trott Feb 16 '12 at 00:02
  • I did not find a workaround sorry. We eventually just stopped using google analytics, and we avoid putting code near history.back(). – DurhamG Feb 16 '12 at 06:32
  • I can't specifically remember having the same problem, but looking through the JavaScript for a HTML5 app I built (year and half ago now), I delegate calls to Google Analytics through a function that I just call at the end of other functions/calls that need it. – cchana Mar 12 '12 at 15:09
  • Does using window.onhashchange in place of window.onpopstate change anything? @RTB – xdumaine Jul 23 '12 at 17:07

3 Answers3

2

Try wrapping the call to _gaq.push() in a async timeout of 0:

$('#my-back-button').bind('tap', function() {
    setTimeout(function() {
         _gaq.push(['_trackEvent', 'mycategory', 'myaction']);
    }, 0);
    history.back();
    return false;
});

This will allow history.back() to execute first before Google Analytics potentially affects the history stack.

dmck
  • 7,801
  • 7
  • 43
  • 79
  • This works for me, verry nice. Can @DurhamG confirm if this also works for him? Then i will award you the bonus. – RTB Jul 24 '12 at 10:15
1

Hm, okay a really nasty one: what happens if you wrap _gaq.push() into a new function and leave history.go() just where it is?

Anze Jarni
  • 1,141
  • 7
  • 7
1

Maybe the call to google analytics adds a new entry to the history stack and history.back() just brings you to the page you are at the moment.

Or GA gives a new scope to history.

Try calling history.back() twice or use top.history.back() or window.history.back() or self.history.back()

yunzen
  • 32,854
  • 11
  • 73
  • 106