9

On the official site it is said:

When a notebook is opened, its “computational engine” (called the kernel) is automatically started. Closing the notebook browser tab, will not shut down the kernel, instead the kernel will keep running until is explicitly shut down."

Is it possible to configure the iPython server so that the kernel is killed together with the associated tab?

Peter Wood
  • 23,859
  • 5
  • 60
  • 99
Nikolay Gromov
  • 302
  • 2
  • 9
  • 1
    Some javascript would do it, but it would be the [`onunload`](http://stackoverflow.com/questions/3888902/javascript-detect-browser-close-tab-close-browser) event, so it would also fire if you followed a link or used the back button. – Peter Wood Sep 28 '15 at 14:32
  • 1
    How will I insert extra HTML code into the notebook template? And what is the API exactly to kill the current kernel? I can probably deduce it from javascript console. – Nikolay Gromov Sep 28 '15 at 14:51
  • 1
    User could add any javascript in the `profile/static/custom/custom.js` file. Will try with this. – Nikolay Gromov Sep 28 '15 at 15:03

3 Answers3

6

After some research and numerous tries the solution is extremely simple. Add at the end of the file profile/static/custom/custom.js the following code:

$( window ).unload(function() {
  IPython.notebook.kernel.kill();
});

Works for me perfectly! (tried on Chrome)

Nikolay Gromov
  • 302
  • 2
  • 9
3

I think IPython.notebook.session.delete() is better than IPython.notebook.kernel.kill().

window.addEventListener('unload', function() {
    // For Firefox
    IPython.notebook.session.delete();
});

window.onbeforeunload = function () {
    // For Chrome
    IPython.notebook.session.delete();
};

Reason

Because kernel.kill() will just kill kernel. It won't tell notebook's sessionmanager about killing it. So after killing, sessionmanager will raise KernelError when you'll reopen the same ipynb file which you closed by kernel.kill() (closed tabs or windows).

About unload

On GoogleChrome, unload events won't be fired on moving pages. So, I think you should also hook beforeunload event

But hooking by addEventListener('beforeunload', ...) didn't work. So I tried window.onbeforeunload = and it works fine.

hirokiky
  • 156
  • 5
  • do you know if there is a different way to do this now? I tried this as well as Jupyter.notebook.session.delete(); but none of it works on chrome to actually stop the kernel. And when I just do it in a %%javascript cell browser console says IPython and Jupyter are both undefined. – kilgoretrout May 28 '21 at 05:28
2

You can write an extension in jupyter (more about jupyter notebook extensions). I can't find any information about notebook extensions in earlier versions of IPython. However, Notebook extensions are customisable and much more prettier than custom.js

Be careful with unload. My chrome 43.0.2357.130 does not run unload on redirect.

I wanted to write comment for Nikolay answer, but I don't have enough points...