boardgames_tracker / src /analytics.py
RandomCatLover's picture
Add Umami page-view tracking
40f139d
Raw
History Blame Contribute Delete
1.25 kB
import streamlit as st
# Not sensitive -- an analytics site ID is plain HTML visible in any page's
# source, so this lives as a code constant rather than a secret/env var.
_UMAMI_SCRIPT_URL = "https://umami-acsk4kc0kw04o4ww4gosgoos.c.ai-man.cc/script.js"
_UMAMI_WEBSITE_ID = "ae40c7e5-ca49-4786-b185-e0a90f337e55"
_SCRIPT_TAG_ID = "umami-analytics-script"
def inject_umami() -> None:
"""Injects the Umami tracking script into the page.
st.html renders directly into the top-level DOM (unlike
components.html, which sandboxes content in its own iframe -- Umami
would then only ever see a meaningless "iframe page" instead of real
pageviews). Guarded by an element id so a Streamlit rerun never injects
a second copy or fires a duplicate pageview.
"""
st.html(
f"""
<script>
if (!document.getElementById('{_SCRIPT_TAG_ID}')) {{
var s = document.createElement('script');
s.id = '{_SCRIPT_TAG_ID}';
s.defer = true;
s.src = '{_UMAMI_SCRIPT_URL}';
s.setAttribute('data-website-id', '{_UMAMI_WEBSITE_ID}');
document.head.appendChild(s);
}}
</script>
""",
unsafe_allow_javascript=True,
)