|
11 | 11 | const url = window.location.href; |
12 | 12 | const urlParams = new URLSearchParams(window.location.search); |
13 | 13 | 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 | + |
14 | 61 | function installGoogleAnalytics() { |
15 | 62 | if(gaReady){ |
16 | 63 | return ; |
|
0 commit comments