Skip to content

Commit 64970ba

Browse files
authored
ga focus handling
1 parent d1ed97b commit 64970ba

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

desktop-metrics.html

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,53 @@
1111
const url = window.location.href;
1212
const urlParams = new URLSearchParams(window.location.search);
1313
const reloadedOnce = urlParams.get('reloadedOnce');
14+
15+
/**
16+
* GA doesn't log engagement metrics if the page is in focus. Since we are a hidden page, we will take over
17+
* the global event handlers and trigger synthetic focus events to make ga think that it has focus.
18+
*/
19+
function patchGlobalFocusHandlers() {
20+
let gaFocusCallback, focusCallbackDone;
21+
window.savedEventListener = window.addEventListener;
22+
savedEventListener('focus', (focusEvent)=>{
23+
gaFocusCallback.call(this, focusEvent);
24+
focusCallbackDone = true;
25+
});
26+
27+
window.addEventListener = function (eventName, fn, globalEvFlag) {
28+
if(eventName === 'focus'){
29+
const focusEvent = new Event('focus', {
30+
view: window,
31+
bubbles: true,
32+
cancelable: true,
33+
isTrusted: true,
34+
cancelBubble: false,
35+
composed : false,
36+
defaultPrevented: false,
37+
returnValue: true
38+
});
39+
document.body.focus();
40+
setTimeout(()=>{
41+
gaFocusCallback = fn;
42+
// first lets try to trigger the actual saved savedEventListener programmatically
43+
window.dispatchEvent(focusEvent);
44+
}, 500);
45+
setTimeout(()=>{
46+
// the event wasnt generated, so we trigger it manually. This is not preferred as the target and
47+
// other important properties of the event are readonly and cannot be overwritten.
48+
if(!focusCallbackDone){
49+
gaFocusCallback.call(window.document.body, focusEvent);
50+
}
51+
}, 1000);
52+
} else if(eventName === 'blur'){
53+
// swallow this event as ga will not track engagement if not focused.
54+
} else {
55+
window.savedEventListener(eventName, fn, globalEvFlag);
56+
}
57+
}
58+
}
59+
patchGlobalFocusHandlers();
60+
1461
function installGoogleAnalytics() {
1562
if(gaReady){
1663
return ;

0 commit comments

Comments
 (0)