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?

1 Like

Hi @Renata_Cavalcanti,

Thanks for posting!

Have you checked out the following resources?

I would also recommend checking out Streamlit Analytics.

Caroline :balloon:

3 Likes

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
5 Likes

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

Thank you, @Caroline !!

3 Likes

Given that this is so high in the google search i just wanted to say that this works for me. Thanks @Renata_Cavalcanti

2 Likes

Ok, 2023, this code works:

st.markdown(
    """
        <!-- 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>
    """, unsafe_allow_html=True)

My version:

$ streamlit --version
Streamlit, version 1.17.0
2 Likes

Mine doesn’t work. This is my code:

def google_analytics():
    # Add Google Analytics code to the header
    ga_code = """
    <!-- Google tag (gtag.js) -->
    <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>
    """
    components.html(
        ga_code,
        width=0,
        height=0
    )  # JavaScript works

def page_header():

    st.set_page_config(page_title="Title", page_icon="images/logo.png")
    google_analytics()
    header = st.container()
    with header:
        logo = Image.open("images/logo.png")
        st.image(logo, width=300)


# Define the main function to run the app
def main():

    # Render the page header
    page_header()

    .....

if __name__ == "__main__":
    main()
1 Like

:wave:Hi @gahnert,

Thanks for posting this. Just to check: do you insert that script in your streamlit app or do you need to go into the back end Streamlit source files to do this?

Reason I ask is that some solutions require you to edit the source files.

I have a multipage app. If you’re just embedding your code in your app, do you need to include this script on every page or do you just call it once?

Thanks in advance for any help!

2 Likes

Hi @Renata_Cavalcanti , are you deploying your app in Streamlit community cloud?

I have been trying to integrate an app of mine that is deployed in community cloud with Google Analytics, but it seems that the virtual machine that hosts the app doesn’t allow my script to add the JS script on the top of the index.html file.

Btw, because of your name I assume you’re brazilian, if so and if you want to reply in portuguese, feel free to.

Thanks in advance.

1 Like

@VirtuaPT is your app deployed in Streamlit community cloud? Or other deploy service?

1 Like

It’s on AWS. It’s still working. Would prefer an official solution thought

1 Like

I don’t mind if it’s not an official solution, just if it works on Streamlit community cloud, but I gave that solution (the one that works for you) a go and it doesn’t.

I surely believe that it works on AWS, because here locally it also does.

Anyways, I appreciate your reply

1 Like

This is not working because the script is inserted inside the body and not within the header.

1 Like