Search code examples
pythongoogle-analyticsstreamlit

Google Analytics is not working on Streamlit Application


I have built a web application using streamlit and hosted it on the Google Cloud Platform (App Engine). The URL is something like https://xxx-11111.uc.r.appspot.com/ which is given for the Stream URL.

I enabled Google Analytics 2 days back but apparently, it is not set up correctly.

It was given that I need to add in the head tag.

This is the code where I added the Google Analytics tag...

What is wrong??

def page_header():
    st.set_page_config(page_title="xx", page_icon="images/logo.png")
    header = st.container()
    with header:
        # Add banner image
        logo = Image.open("images/logo.png")
        st.image(logo, width=300)

        # Add Google Analytics code to the header
        ga_code = """
        <!-- Google tag (gtag.js) -->
        <script async src="https://www.googletagmanager.com/gtag/js?id=G-xxxxxx"></script>
        <script>
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());

            gtag('config', 'G-xxxxxx');
        </script>
        """
        st.markdown(ga_code, unsafe_allow_html=True)


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

    # Render the page header
    page_header()

    .....

if __name__ == "__main__":
    main()

Solution

  • One way to implement Google Analytics into your GAE Streamlit app would be to add the GA global site tag JS code to the default /site-packages/streamlit/static/index.html file

    NOTE: This script should be run prior to running the streamlit server

    from bs4 import BeautifulSoup
    import shutil
    import pathlib
    import logging
    import streamlit as st
    
    
    def add_analytics_tag():
        # replace G-XXXXXXXXXX to your web app's ID
        
        analytics_js = """
        <!-- Global site tag (gtag.js) - Google Analytics -->
        <script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
        <script>
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', 'G-XXXXXXXXXX');
        </script>
        <div id="G-XXXXXXXXXX"></div>
        """
        analytics_id = "G-XXXXXXXXXX"
    
        
        # Identify html path of streamlit
        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=analytics_id): # if id not found within html file
            bck_index = index_path.with_suffix('.bck')
            if bck_index.exists():
                shutil.copy(bck_index, index_path)  # backup recovery
            else:
                shutil.copy(index_path, bck_index)  # save backup
            html = str(soup)
            new_html = html.replace('<head>', '<head>\n' + analytics_js) 
            index_path.write_text(new_html) # insert analytics tag at top of head