Skip to content

Commit 5f5485d

Browse files
committed
fix: ga metrics not showing up in relatime user dashboards
1 parent de87c83 commit 5f5485d

File tree

1 file changed

+33
-5
lines changed

1 file changed

+33
-5
lines changed

src/desktop-metrics.html

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,22 @@
55
<meta name="robots" content="noindex, nofollow">
66
<title>Desktop Metrics logger with Google Analytics</title>
77
<script>
8-
let gaReady = false;
9-
function installGoogleAnalytics(analyticsID) {
10-
if(!analyticsID || gaReady){
8+
const SAVED_GOOGLE_ANALYTICS_DESKTOP_KEY = "SAVED_GOOGLE_ANALYTICS_DESKTOP_KEY";
9+
let gaReady = false, loadedGoogleAnalyticsID;
10+
11+
const url = window.location.href;
12+
const urlParams = new URLSearchParams(window.location.search);
13+
const reloadedOnce = urlParams.get('reloadedOnce');
14+
function installGoogleAnalytics() {
15+
if(gaReady){
1116
return ;
1217
}
18+
const analyticsID = localStorage.getItem(SAVED_GOOGLE_ANALYTICS_DESKTOP_KEY);
19+
if(!analyticsID) {
20+
console.error("No analytics id found to init ga, waiting for phcode to send ids to init...");
21+
return;
22+
}
23+
loadedGoogleAnalyticsID = analyticsID;
1324
// ga primer scripts
1425
window.dataLayer = window.dataLayer || [];
1526
window.gtag = function() {
@@ -29,10 +40,24 @@
2940
gaReady = true;
3041
}
3142

43+
installGoogleAnalytics();
44+
45+
function reloadOnce() {
46+
// we have to do this as ga seems to miss points in real time analytics dashboard if ga is not inited
47+
// at page load time. So we reload once to make metrics show up in ga real time dashboard.
48+
let currentUrl = new URL(window.location);
49+
if (!currentUrl.searchParams.has('reloadedOnce')) {
50+
currentUrl.searchParams.set('reloadedOnce', 'true');
51+
window.location.href = currentUrl.href;
52+
}
53+
}
54+
55+
3256
async function processRequest(event) {
3357
const payload = event.payload;
34-
if(!gaReady) {
35-
installGoogleAnalytics(payload.analyticsID);
58+
if(payload.analyticsID && loadedGoogleAnalyticsID !== payload.analyticsID) {
59+
localStorage.setItem(SAVED_GOOGLE_ANALYTICS_DESKTOP_KEY, payload.analyticsID);
60+
installGoogleAnalytics();
3661
}
3762

3863
for(let eventPayload of payload.events) {
@@ -42,6 +67,9 @@
4267
'value': eventPayload.count
4368
});
4469
}
70+
if(!reloadedOnce) {
71+
setTimeout(reloadOnce, 1000);
72+
}
4573
}
4674
window.__TAURI__.event.listen("health", processRequest);
4775
setInterval(async ()=>{

0 commit comments

Comments
 (0)