Widget Button to open url

Background: As apart of an application I do have links being displayed that one can click on to go to external pages (to the voila page), however in an attempt to make it a bit more presentable I wanted to see if I could just make some of the links into buttons.

I am attempting to create a widget button that will open a url.
This is run on a remote system (jupyterlab on a remote server) not local, as such using webbrowser.open will not work.

If I just run this on the remote system it works:

import ipywidgets as widgets
from IPython.display import display, Javascript

def window_open(url):
    display(Javascript(f'window.open("{url}");'))

window_open('https://www.google.com')

Then the new window opens fine.

When I wrap this in a button, it does not work:

import ipywidgets as widgets
from IPython.display import display, Javascript

def window_open_button(url):
    display(Javascript(f'window.open("{url.tooltip}");'))

ss = widgets.Button(description="hello", tooltip='https://www.google.com')
ss.on_click(window_open_button)
ss

When I click on the button, I ust get an entry in the jupyterlab log window saying:
<IPython.core.display.Javascript object>

image

I am not sure how to reason through why this is happening, any ideas of why and what a solution could be?

This is because the notebook does not know where to display the Javascript object, so instead it logs it in the console to let you know that something is amiss. One solution would be to point your display to a specific Output:

import ipywidgets as widgets
from IPython.display import display, Javascript

out = widgets.Output()


def window_open_button(url):
    with out:
        display(Javascript(f'window.open("{url.tooltip}");'))


ss = widgets.Button(description="hello", tooltip='https://www.google.com')
ss.on_click(window_open_button)

with out:
    display(ss)
out
2 Likes

Or, make a plain-old link look like a button, e.g. <a href="https://jupyter.org" target="_blank">hello</a> and use CSS to make it look like a button. For folks that already have middle-click-muscle-memory, this might even be more familiar.

3 Likes

Thank you for educating me on the reasons for that behavior and a solution that works.