How to get Notebook URL and Name

How can I get the Notebook’s Path and Name from @jupyterlab/notebook extension.

Below is the sample code in which I’m trying to obtain path and name.

export class ButtonExtension implements DocumentRegistry.IWidgetExtension<NotebookPanel, INotebookModel>{
    createNew(widget: NotebookPanel, context: DocumentRegistry.IContext<INotebookModel>): void | IDisposable {
        let mybutton = new ToolbarButton({
            label: 'Show Page Url',
            onClick: () => console.log(**<get Notebook's full-path / Name >**)
        });
        widget.toolbar.insertItem(10, 'mybutton', mybutton);
        return mybutton
    }
}

panel.context.contentsModel (an Contents.IModel) has both path and name attributes.

1 Like

Thanks it works.

With name property it get’s the notebook’s name. But for path it doesn’t give the relative path to the notebook.

In below screenshot you can see instead of giving the path as /lab/tree/Untitled2.ipynb it just prints the name of the notebook.

Here’s the code:

export class ButtonExtension implements DocumentRegistry.IWidgetExtension<NotebookPanel, INotebookModel>{
    createNew(widget: NotebookPanel, context: DocumentRegistry.IContext<INotebookModel>): void | IDisposable {
        let mybutton = new ToolbarButton({
            label: 'Show Page Url',
            onClick: () => console.log(widget.context.contentsModel?.path)
        });
        widget.toolbar.insertItem(10, 'mybutton', mybutton);
        return mybutton
    }
}

The path is the “contents” path: with PageConfig, you can use that to derive:

  • the API path, e.g. <base_url>/api/contents/<path>
  • the download path, e.g. <base_url>/files/<path>
  • the shareable link <base_url>/lab/tree/<path>?token=<token>
    • in fact, this is a feature of PageConfig.getUrl: example
3 Likes

You can get notebook path it by using widget from IFileBrowserFactory from ‘@jupyterlab/filebrowser’;

import { IFileBrowserFactory } from '@jupyterlab/filebrowser';
function widget(factory: IFileBrowserFactory){
      const { tracker } = factory;
      const widget = tracker.currentWidget;
      if (!widget) {
        return;
      }
      //this will give the username 
      const serverRoot = (app as any)?.paths?.directories?.serverRoot;
     //this will give the notebook Path
      const localPath = widget.selectedItems().next()!.value.path;
}
1 Like