4

I would like to track in Google Analytics a UI I built with Streamlit. According to Google Analytics, the following needs to be added into the <head> section of the HTML.

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

As I do not have any html file in my code architecture, I included the following Streamlit line in my main .py file:

google_analytics_js = '[previous_html_code]'
st.components.v1.html(google_analytics_js)

The website is unfortunately not tracked. Any help on this would be greatly appreciated.

Yves
  • 181
  • 7
  • [How to add Google Analytics or JS code in a Streamlit app?](https://discuss.streamlit.io/t/how-to-add-google-analytics-or-js-code-in-a-streamlit-app/1610/27) – RoseGod Dec 29 '21 at 15:27
  • Thanks. I saw that yes, but no discussed solution in that page worked in my case – Yves Dec 30 '21 at 10:43
  • Did you find a solution? If yes, what is it? – DeadPool Apr 19 '23 at 07:03

1 Answers1

0

Since the component HTML will be added to an iframe, you need to allow its script to access the parent:

<script crossorigin='anonymous'>
add script
</script>

In addition to that, whenever the script accesses window or document, you should use parent.window and parent.document.

kepler
  • 1,712
  • 17
  • 18