Closing a stand-alone server by closing its "show-generated" tab in the browser

Goal: I’m trying to close a server when the browser tab is closed or when the user clicks on some sort of “Quit” button.

Longer Description: In the case where I create a stand-alone bokeh server I am able to create a “Quit” Button which will io_loop.stop() in its callback but that leaves the client-side plot window intact. I assume that window.close() in a CustomJS callback won’t work (because the window was not created by the page’s javascript) and furthermore I don’t know how to generate a combination of javascript and Python in response to a user generated event.

The best solution, as far as I can tell (and I know nothing of the various hooks that might be available) would be to add a callback to onbeforeunload which triggers some server-side callback equivalent to that of a my aforementioned “Quit” button. But (1) I don’t know how to inject “global” javascript code to a plot (not associated with a specific callback) and (2) I don’t know how to use the websocket/REST API to trigger a specific callback (I suppose I can call the click() method on an invisible button, but that worries me since it would be happening during the unload so the event might never be triggered)…


i have a similar if not identical problem as the OP. i have a bokeh application as described here. it is launched as a background process via a shell script. only one user ever accesses it at a time. when they close the browser window i want a function to be called that cleans some things up and then exits that bash process. a Quit button that closes the browser window would optionally be nice. is there a way to do this? thanks.

Well, there’s nothing stopping you from calling e.g. sys.exit() from a Bokeh app callback. Not normally something you’d ever want to do from Bokeh app code but it might be reasonable under the assumptions in this situation. As for closing the browser window, I think you will have to do some research as it seems to vary across browsers. There is window.close() that a CustomJS callback could call, but at least in my experience it was flaky (e.g. I had to call it twice to work on Chrome).

thanks! that works. i was just wondering whether it was advised to more cleanly exit, by shutting down tornado for example. but if sys.exit() works…

Well it’s Python, so there’s always some way, but generally speaking Bokeh app code does not have any easy or direct access to the Tornado application. We could consider adding some API to support this use shutdown case more gracefully, but I’d want to put it behind some affirmative flag to enabled it like --allow-shutdown or something. Fee free to open a GH issue to discuss (especially if you are interested in working on it)