Skip to content

Instantly share code, notes, and snippets.

@Hu-Wentao
Last active November 16, 2024 19:11
Show Gist options
  • Select an option

  • Save Hu-Wentao/f546cb530c6a7dec936e35a3089db45f to your computer and use it in GitHub Desktop.

Select an option

Save Hu-Wentao/f546cb530c6a7dec936e35a3089db45f to your computer and use it in GitHub Desktop.
Streamlit: inject ms-Clarity 通过修改st源码,为st注入clarity.ms
from bs4 import BeautifulSoup
import pathlib
import shutil
import streamlit as st
CLARITY_SCRIPT = """
<script type="text/javascript">
(function(c,l,a,r,i,t,y){
c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};
t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i;
y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);
})(window, document, "clarity", "script", "<--- your clarity script id --->");
</script>
"""
INJECTION_COMMENT = "<!-- Clarity script injected -->"
def inject_track():
index_path = pathlib.Path(st.__file__).parent.joinpath('static', 'index.html')
soup = BeautifulSoup(index_path.read_text(), features="html.parser")
if INJECTION_COMMENT not in str(soup):
bck_index = index_path.with_suffix('.bak') # backup index.html to index.html.bak
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' + CLARITY_SCRIPT + INJECTION_COMMENT)
index_path.write_text(new_html)
print('Clarity inject Done.')
else:
print('Clarity injected. Skipping.')
if __name__ == '__main__':
inject_track()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment