dash-extensions icon indicating copy to clipboard operation
dash-extensions copied to clipboard

EventListener using beforeunload

Open HyprValent opened this issue 3 years ago • 1 comments

Hello!

I am trying to utilize the EventListener component in dash-extensions to have my dash app initiate a callback when the user unloads the page (either through exiting or refreshing the tab). My understanding is that this would be accomplished by running the code using onbeforeunload event listeners. But I'm kind of confused how this would be translated over to an EventListener object through this Python package. I have tried a quick test of this functionality in a minimal Dash app, but I don't see anything in the console that would indicate the callback is being fired.

app = Dash(__name__)

event = [{"event": "beforeunload", 'props': ['view']}]

app.layout = html.Div([
    html.Button('Press', id='console-button'),
    html.Div(id='clicked', children="Yes"),

    EventListener(
        events=event, logging=True, id='el'
    )
])

@app.callback(
    Output('success-div', "children"),
    Input('el','n_events'),
    State('el', 'event'),
    prevent_initial_call=True
)
def unload_files(n_clicks, e):
    if e is None:
        raise PreventUpdate()

    print('Unloaded')
    return 'Unloaded'

if __name__ == '__main__':
    app.run_server(debug=True)

I'm probably missing something very simple, but I would appreciate the assistance!

HyprValent avatar Nov 16 '22 20:11 HyprValent

I am not sure this is possible, I suspekt that this event is executed after Dash itself has been unloaded.

emilhe avatar Nov 16 '22 22:11 emilhe