Google Analytics and Streamlit

Hello, I am trying to connect my Streamlit app with Google Analytics, but nothing works. Is there any way this could be happening?

Hi @Renata_Cavalcanti,

Thanks for posting!

Have you checked out the following resources?

I would also recommend checking out Streamlit Analytics.

Caroline :balloon:

Hi @Caroline !! Thanks for your answer! Yes, I have, but google analytics keeps falling, it stays active for a few and then it says that it is not active.

This is my code, and it is on the streamlit app script

def inject_ga():
    GA_ID = "google_analytics"


    GA_JS = """
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-**********"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', 'G-**********');
    </script>
    """

    # Insert the script in the head tag of the static template inside your virtual
    index_path = pathlib.Path(st.__file__).parent / "static" / "index.html"
    logging.info(f'editing {index_path}')
    soup = BeautifulSoup(index_path.read_text(), features="html.parser")
    if not soup.find(id=GA_ID): 
        bck_index = index_path.with_suffix('.bck')
        if bck_index.exists():
            shutil.copy(bck_index, index_path)  
        else:
            shutil.copy(index_path, bck_index)  
        html = str(soup)
        new_html = html.replace('<head>', '<head>\n' + GA_JS)
        index_path.write_text(new_html)


inject_ga()

I also included:

import pathlib
from bs4 import BeautifulSoup
import logging
import shutil

Ok, just an update. It is working now, I think I just had to wait.

Thank you, @Caroline !!

1 Like