Using Google Analytics with Dash App

Hi,

So I recently started using GA4 with my Dash app published on Heroku and I have been trying to use it to track certain interactions. Because my app is run as a single page application, I only retrieve information on GA when the page is first loaded. I saw that to track interactions on single page applications with GA, it is recommended that you execute the GA script again whenever the page is interacted with.

Right now, to embed GA4 on my page, I have used this code:

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

          gtag('config', #########);
        </script>
        {%metas%}
        <title>{%title%}</title>
        {%favicon%}
        {%css%}
    </head>
    <body>
        {%app_entry%}
        <footer>
            {%config%}
            {%scripts%}
            {%renderer%}
        </footer>
    </body>
</html>"""

Is there any way I can execute the index_string command in a callback or use another method to execute the GA4 script in a Dash callback?

Thanks for the help!

FYI

Thank you for the reply

I may be missing something in the article, but is there a way that I can execute the index_string method again while in a callback. I would like to execute the GA4 script every time the callback is used so I can gather certain interactions involving that callback.

You may consider the Clientside Callbacks.

from dash.dependencies import Input, Output

app.clientside_callback(
    """
    function(largeValue1, largeValue2) {
        return someTransform(largeValue1, largeValue2);
    }
    """,
    Output('out-component', 'value'),
    Input('in-component1', 'value'),
    Input('in-component2', 'value')
)
2 Likes

Thank you again for the help, clientside callbacks worked. For anyone looking for an example, here is what worked for me:

app.clientside_callback(
    """
    function(tab_value) {
        if (tab_value != null){
            document.title = title + tab_value.properties.Index
            window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);
          dataLayer.push({
              'pageTitle' : 'test'
          });}
          gtag('js', new Date());

          gtag('config', '########');
        }
        else{
            document.title = title
        }
    }
    """,
    Output('blank-output', 'children'),
    Input('geojson', 'click_feature')
)

2 Likes