-
Notifications
You must be signed in to change notification settings - Fork 2
/
googletag_inject.py
33 lines (28 loc) · 962 Bytes
/
googletag_inject.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
from bs4 import BeautifulSoup
import pathlib
import shutil
import streamlit as st
GA_ID = "google_analytics"
GA_SCRIPT = """
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-J39CF4DQL0"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-J39CF4DQL0');
</script>
"""
def inject_ga():
index_path = pathlib.Path(st.__file__).parent / "static" / "index.html"
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_SCRIPT)
index_path.write_text(new_html)
# inject_ga()