File size: 1,248 Bytes
40f139d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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,
    )