Communicating back to Streamlit which hyperlink was clicked

Hi i have a question. I built a Streamlit app where a part of a pandas data frame is printed according to some filtering and ranking criteria. Each line of that data frame contains a clickable html link which redirects to a document (out of overall roughly 50’000) that will be opened outside of the app. As directly st.write-ing doesn’t support hyperlinks (yet) I took a df.to_html()-approach similar to the one mentioned here.

Here a minimum code example for the df:

import streamlit as st
import pandas as pd
df = pd.DataFrame.from_dict({'link': '<a href="https://www.google.com" id="ggl"> Google </a>', '<a href="https://www.facebook.com" id="fb"> Facebook </a>', 'id': [1, 2]})
st.write(df.to_html(escape=False, index=False, show_dimensions=True), unsafe_allow_html=True)

which gives me this display:


Now my question: Amongst other things I would like to log which links were clicked in that table. The logger itself already works, I just hang at one particular bit: how can I communicate back to Streamlit which of the links within that displayed df was clicked?

Any Ideas? Do I have to e.g. define an onClick()-Javascript function and build my own Streamlit component or is there an easier way?

Found a solution myself :wink: used experimental get_query_params() and set_query_params() features.

import streamlit as st
import pandas as pd
import webbrowser

df = pd.DataFrame.from_dict({'link': ['<a href="?url=google" target="_top"> Google </a>',
                                  '<a href="?url=facebook" target="_top"> Facebook </a>'], 'id': [1, 2]})
df = df.to_html(escape=False, index=False, show_dimensions=True)
h = '<head><style type="text/css"></style></head>'
bo = '<body><div style = "height:200px;width:100%;overflow:auto;">'
bc = '</div></body>'
st.write(h + bo + df + bc, unsafe_allow_html=True)
para = st.experimental_get_query_params()
if 'url' in para.keys():
    st.experimental_set_query_params()
    st.write(f'you just clicked {para.get("url")[0]}')
    webbrowser.open_new_tab(f'https://{para.get("url")[0]}.com')
3 Likes