Sunday, June 2, 2024
131
rated 0 times [  133] [ 2]  / answers: 1 / hits: 7787  / 10 Years ago, mon, may 5, 2014, 12:00:00

I'm trying to accomplish tracking an event when a user leaves the page with Google Analytics (analytics.js). Though it is unknown how the user will leave, it may be because of an external link or just closing the tab. So my thought was to hook onto the beforeunload or unload event and then:



window.addEventListener(beforeunload, function() {
ga('send', 'event', 'some', 'other', 'data');
});


Now my question is, will the request to the GA server be synchronous or can I somehow force that behaviour with the hitCallback property? If that is not possible, how else can I achieve this? Preferably without having to set a timeout or fixed waiting time for the user!


More From » google-analytics

 Answers
6

The request will not be synchronous, GA tracking calls never are.



The only way to ensure the call completes is to make sure the page stays open long enough - for an event on a link you would normally do this with a timeout potentially combined with a hitCallback, as you mentioned.



The only way to keep a window open when the user closes a tab is to return a value from your beforeunload handler, which will prompt a Confirm Navigation alert. That would be a really bad solution just to track a GA event, obviously.


[#45534] Sunday, May 4, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brennanm

Total Points: 510
Total Questions: 103
Total Answers: 95

Location: Nicaragua
Member since Tue, Dec 8, 2020
4 Years ago
;