Add code cell notebook from extension

I am trying to build an extension which has a widget. This widget has a button, clicking on which I want to add a new code cell in the currently active notebook. I am using INotebookTracker and NotebookModel to achieve this, but the code cell is not getting added to the notebook. Here’s the code I am using to add the new code cell:
this._tracker.currentWidget?.model?.contentFactory.createCodeCell({})

Can someone please tell me what am I missing here?

I have been using this approach successfully:

    const cell = this._notebookPanel.content.model.contentFactory.createCell(
      this._notebookPanel.content.notebookConfig.defaultCell,
      {}
    );

    this._notebookPanel.content.model.cells.insert(0, cell);

It think the approach you are using might be better; however. It looks like you may just need to insert the new cell.

I was able to solve this issue by passing this object as the parameter to createCodeCell() method:

{cell: {
            cell_type: 'code',
            source: [
                `print(\'hello\')`,
           ],
           metadata: {},
         }}
1 Like