首页 > 解决方案 > 如何从 JupyterLab 扩展激活方法访问笔记本?

问题描述

前段时间我为 JupyterNotebook 写了一个扩展。现在我想为 JupyterLab 改编它。

为了访问我使用的当前打开的笔记本:

var notebook = Jupyter.notebook;
var firstCell = notebook.get_cells()[0];

=> Jupyterlab 对应的代码是什么?

module.exports = [{
    id: 'jupyterlab_workspace_module',
    autoStart: true,
    activate: function(app) {
       //app.notebook is not defined
       var notebook = getNotebook(app); // <= how to implement this?
    }
}];

标签: javascriptjupyterjupyter-lab

解决方案


var notebookPanel = __getFirstVisibleNotebookPanel(app);
var notebook = notebookPanel.content;
var cell = notebook.activeCell;

function __getFirstVisibleNotebookPanel(app){
    var mainWidgets = app.shell.widgets('main');
    var widget = mainWidgets.next();
    while(widget){
        var type = widget.constructor.name;
        if(type == 'NotebookPanel'){  //other wigets might be of type DocumentWidget
            if (widget.isVisible){
                return widget;
            }
        }
        widget = mainWidgets.next();
    }
    return null;
}

推荐阅读