How to get the current notebook panel?

Hi,

I am trying to make an extension that creates and opens up an .ipynb file automatically. I need to get the current notebook panel after opening up the file. I have found that I can use INotebookTracker to get the current notebook

function activate(app:JupyterFrontEnd, notebookTracker: INotebookTracker) {
    const nbPanel1: any = notebookTracker;
    console.log(nbPanel1)
}

I can see from the console.log that nbPanel1 contains currentWidget, which indeed points to the current NotebookPanel which contains my current file (“renamed.ipynb”) opened.

However, when I try to extract just the widget i.e. NotebookPanel, which from the documentation here it seems I should be able to do:

function activate(app:JupyterFrontEnd, notebookTracker: INotebookTracker) {
    const nbPanel1: any = notebookTracker;
    console.log(nbPanel1);
    const nbPanel2: any = notebookTracker.currentWidget;
    console.log(nbPanel2);
}

From the console log nbPanel2 does not return the NotebookPanel that I saw in nbPanel1's currentWidget value as expected, instead it returns null.

Why is it not able to return the currentWidget object i.e. the NotebookPanel that I saw in nbPanel1?

Is there a better way to extract the current NotebookPanel?

Thank you for your help!

Very close: further down that API page, it hints at how one might listen for when the widget changes:

function activate(app:JupyterFrontEnd, notebookTracker: INotebookTracker) {
  notebookTracker.currentChanged.connect((tracker, panel) => {
    console.log(panel);
  });
}
  • the type on that panel, like currentWidget might still be null (e.g. when all of the notebooks have closed).
  • this is a signal
    • these are worth understanding, as most of the “good stuff” in the core functionality can be efficiently observed through this means
2 Likes

Awesome, this works perfectly. Thanks for the answer and explanations! It is very much appreciated :blush: