Problem of linking local javascript file


#1

Hello,

I would like to know whether there is a way to link local javascript file in Dash application. I’m using offline mode (no internet connection), and only on local host server.

I’ve tried the suggestions of Chris (How do I use Dash to add local css?), and I’ve indeed succeeded in adding local css and image files with dash_html_components, e.g. html.Link() and html.Img(). But html.Script() seems to do nothing. Does anyone have any experience on using a local javascript file within Dash app? Thanks.


#2

It’s hacky, but I’ve put a couple short bits of javascript in a data uri, and that seemed to work… but hopefully there’s a more elegant solution:

from base64 import urlsafe_b64encode

def _to_data_uri(s, mime):
    uri = (
        ('data:' + mime + ';base64,').encode('utf8') +
        urlsafe_b64encode(s.encode('utf8'))
    ).decode("utf-8", "strict")
    return uri

app.scripts.append_script({
    'external_url': _to_data_uri("""
        alert('hi!');
    """)})

#3

Maybe I’m missing something obvious here… How do you actually execute the appended javascript function?

For example, is it possible to execute the ‘external_url’ script via a Dash/html button? Something like this…

layout = html.Div([
    html.Div(id = 'dummy_div', style={'display': 'none'}),
    html.Button('Click Me!', id = 'run_javascript'),
    ])

@app.callback(
    dash.dependencies.Output('dummy_div', 'children'),
    [dash.dependencies.Input('run_javascript', 'n_clicks')]
    )
def run_javascript(click_event=None):
    ## what do I put here to run 'external_url'?
    return

#4

A script that is included as an external_url will be run when your app loads. As far as I’m aware, there’s no convenient way to trigger arbitrary JS using a callback.


#5

In my case, our Dash app also uses Bootstrap, and it’s the callbacks on those components that I was adding my own javascript for… I’d be a little leery of trying to override Dash’s behavior with my own extras, without really understanding React better.