-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathanalytics.py
34 lines (29 loc) · 1.06 KB
/
analytics.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import pathlib
from bs4 import BeautifulSoup
import shutil
import streamlit as st
def inject_ga():
GA_ID = "google_analytics"
GA_JS = """
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-99ZX6X1MCM"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-99ZX6X1MCM');
</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"
print(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)