After searching all over the web for a simple and elegant solution, but not finding one to my liking, I created a solution to open links in a new tab by clicking on a streamlit button, without using any 3rd party packages.
source code:
from streamlit.components.v1 import html
def open_page(url):
open_script= """
<script type="text/javascript">
window.open('%s', '_blank').focus();
</script>
""" % (url)
html(open_script)
How to use - Simply add the function as an on_click parameter to the streamlit button.
streamlit.button('Open link', on_click=open_page(url))
8 Likes
Wow! I love that workaround, @benceszarka!
Thanks for sharing it with us.
Happy Streamlit-ing! 
Charly
1 Like
Hi @benceszarka
Thanks for sharing the wonderful solution. I really like how you’re using callback to call for the URL on click.
I’d like to suggest a minor tweak to your code by passing the function name to the on_click
parameter (and passing the URL to the args
parameter) instead of using a function call with arguments (open_page(url)
).
Suggested tweak as follows:
st.button('Open link', on_click=open_page, args=('https://streamlit.io',))
In the original solution, the app loads the provided URL as a new page immediately; this happens before clicking on the button.
By tweaking the code, the app loads (the URL is not yet called) and after clicking on the button a new page loads and goes to the URL.
Code of original solution
import streamlit as st
from streamlit.components.v1 import html
def open_page(url):
open_script= """
<script type="text/javascript">
window.open('%s', '_blank').focus();
</script>
""" % (url)
html(open_script)
st.button('Open link', on_click=open_page('https://streamlit.io'))
Code of proposed tweak
import streamlit as st
from streamlit.components.v1 import html
def open_page(url):
open_script= """
<script type="text/javascript">
window.open('%s', '_blank').focus();
</script>
""" % (url)
html(open_script)
st.button('Open link', on_click=open_page, args=('https://streamlit.io',))
4 Likes
Hi.
Due to the limited environment, I distribute streamlit as ‘Network URL’ and use it.
I decided to apply this code a little bit because of the problem that Chrome only runs locally when an external user presses a button.
Can I enter the local pdf file path instead of url in Chrome to open it in a new tab?
I entered a path starting with file:// and ran this code, but it didn’t work.
Hi @Gyunald
Instead of pointing to a local file path, can you serve the PDF from a web server and point to that URL?
No, it’s not a web-supplied pdf.
It’s a file in a network share folder, and we’re trying to access the file faster.
It doesn’t matter if the file is pdf or image.
Thank you.
I used st.download_buton as the next best option. Although downloading the file to an external computer was successful. How is it possible to open a downloaded file right away?
1 Like