-
-
Notifications
You must be signed in to change notification settings - Fork 193
Expand file tree
/
Copy pathdesktop-metrics.html
More file actions
165 lines (152 loc) · 6.87 KB
/
desktop-metrics.html
File metadata and controls
165 lines (152 loc) · 6.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="robots" content="noindex, nofollow">
<title>Desktop Metrics logger with Google Analytics</title>
<script>
// Set __ELECTRON__ flag like index.html does
if(window.electronAppAPI) {
window.__ELECTRON__ = true;
}
const SAVED_GOOGLE_ANALYTICS_DESKTOP_KEY = "SAVED_GOOGLE_ANALYTICS_DESKTOP_KEY";
const SAVED_CUSTOM_USER_ID_KEY = "SAVED_CUSTOM_USER_ID";
let gaReady = false, loadedGoogleAnalyticsID;
let savedCustomUserID = localStorage.getItem(SAVED_CUSTOM_USER_ID_KEY);
const url = window.location.href;
const urlParams = new URLSearchParams(window.location.search);
const reloadedOnce = urlParams.get('reloadedOnce');
/**
* GA doesn't log engagement metrics if the page is in focus. Since we are a hidden page, we will take over
* the global event handlers and trigger synthetic focus events to make ga think that it has focus.
*/
function patchGlobalFocusHandlers() {
let gaFocusCallback, focusCallbackDone;
window.savedEventListener = window.addEventListener;
savedEventListener('focus', (focusEvent)=>{
if (gaFocusCallback) {
gaFocusCallback.call(this, focusEvent);
focusCallbackDone = true;
}
});
window.addEventListener = function (eventName, fn, globalEvFlag) {
if(eventName === 'focus'){
const focusEvent = new Event('focus', {
view: window,
bubbles: true,
cancelable: true,
isTrusted: true,
cancelBubble: false,
composed : false,
defaultPrevented: false,
returnValue: true
});
document.body.focus();
setTimeout(()=>{
gaFocusCallback = fn;
// first lets try to trigger the actual saved savedEventListener programmatically
window.dispatchEvent(focusEvent);
}, 500);
setTimeout(()=>{
// the event wasnt generated, so we trigger it manually. This is not preferred as the target and
// other important properties of the event are readonly and cannot be overwritten.
if(!focusCallbackDone){
gaFocusCallback.call(window.document.body, focusEvent);
}
}, 1000);
} else if(eventName === 'blur'){
// swallow this event as ga will not track engagement if not focused.
} else {
window.savedEventListener(eventName, fn, globalEvFlag);
}
}
}
patchGlobalFocusHandlers();
function installGoogleAnalytics() {
if(gaReady){
return ;
}
const analyticsID = localStorage.getItem(SAVED_GOOGLE_ANALYTICS_DESKTOP_KEY);
if(!analyticsID) {
console.error("No analytics id found to init ga, waiting for phcode to send ids to init...");
return;
}
loadedGoogleAnalyticsID = analyticsID;
// ga primer scripts
window.dataLayer = window.dataLayer || [];
window.gtag = function() {
window.dataLayer.push(arguments);
if(window.dataLayer.length > 500){
window.dataLayer.splice(0, 250); // remove half the elements offline queue guard
}
}
const gaScript = document.createElement('script');
gaScript.async = true;
gaScript.src = `https://www.googletagmanager.com/gtag/js?id=${analyticsID}`;
document.head.appendChild(gaScript);
gtag('js', new Date());
const configParams = {};
if (savedCustomUserID) {
configParams.client_id = savedCustomUserID;
}
gtag('config', analyticsID, configParams);
gaReady = true;
}
installGoogleAnalytics();
function reloadOnce() {
// we have to do this as ga seems to miss points in real time analytics dashboard if ga is not inited
// at page load time. So we reload once to make metrics show up in ga real time dashboard.
let currentUrl = new URL(window.location);
if (!currentUrl.searchParams.has('reloadedOnce')) {
currentUrl.searchParams.set('reloadedOnce', 'true');
window.location.href = currentUrl.href;
}
}
async function processRequest(event) {
const payload = event.payload;
if (payload.customUserID && payload.customUserID !== savedCustomUserID) {
savedCustomUserID = payload.customUserID;
localStorage.setItem(SAVED_CUSTOM_USER_ID_KEY, payload.customUserID);
if (gaReady) {
gtag('config', loadedGoogleAnalyticsID, {
client_id: savedCustomUserID,
send_page_view: false
});
}
}
if(payload.analyticsID && loadedGoogleAnalyticsID !== payload.analyticsID) {
localStorage.setItem(SAVED_GOOGLE_ANALYTICS_DESKTOP_KEY, payload.analyticsID);
installGoogleAnalytics();
}
for(let eventPayload of payload.events) {
gtag('event', eventPayload.eventAct, {
'event_category': eventPayload.category,
'event_label': eventPayload.label,
'value': eventPayload.count
});
}
if(!reloadedOnce) {
setTimeout(reloadOnce, 1000);
}
}
if(window.__TAURI__) {
window.__TAURI__.event.listen("health", processRequest);
setInterval(async ()=>{
// close window if the metrics hidden window and file drop window is the only one around.
const allTauriWindowsLabels = await window.__TAURI__.invoke('_get_window_labels');
if(allTauriWindowsLabels.length === 2 || allTauriWindowsLabels.length === 1){
window.__TAURI__.window.getCurrent().close();
}
}, 1000);
} else if(window.__ELECTRON__) {
window.electronAPI.onHealthMetric((payload) => {
processRequest({ payload });
});
// No cleanup needed - Electron app exits when main windows close
}
</script>
</head>
<body>
Phoenix Desktop Metrics emitter to GA.
</body>
</html>