General API

The Facade APIs available in Univer depend on the document type. This page covers the general APIs, which behave the same way in every document type.

Importing

TypeScript
import { FUniver } from '@univerjs/core/facade'const univerAPI = FUniver.newAPI(univer)

Concepts

Commands

Most operations in Univer are registered with the command system and run through it. Because every operation follows the same path, Univer can support undo, redo, and collaboration.

For the design rationale, see Univer Command System.

Commands

Nearly every operation in Univer is registered with the command system and triggered through it. Centralizing all operations in one place is what makes features such as undo, redo, and collaboration practical.

A command can be understood as a unique "event" inside Univer. For the design details, see command-system.

Listening commands

Univer provides two points at which to listen to a command: before it executes and after it executes.

  • Event.BeforeCommandExecute runs custom logic before the command executes.
  • Event.CommandExecuted runs custom logic after the command executes.

Listening commands before execution

Pass Event.BeforeCommandExecute to FUniver.addEvent to register a preprocessing listener. The listener's code runs before the command executes.

TypeScript
const univerAPI = FUniver.newAPI(univer)univerAPI.addEvent(univerAPI.Event.BeforeCommandExecute, ({ id, type, params }) => {  // Custom logic executed before the command is executed})

To prevent the command from executing, set event.cancel to true in the callback.

TypeScript
const univerAPI = FUniver.newAPI(univer)univerAPI.addEvent(univerAPI.Event.BeforeCommandExecute, (event) => {  event.cancel = true})

Listening commands after execution

Pass Event.CommandExecuted to FUniver.addEvent to register a post-processing listener. Its code runs after the command has executed.

TypeScript
const univerAPI = FUniver.newAPI(univer)univerAPI.addEvent(univerAPI.Event.CommandExecuted, ({ id, type, params }) => {  // Custom logic executed after the command is executed})

Cancel listening

Registering a command listener returns an IDisposable object. Call IDisposable.dispose to destroy it.

Destroy listeners that are no longer in use. Releasing them helps keep the program stable.

TypeScript
const univerAPI = FUniver.newAPI(univer)// Register a listenerconst disposable = univerAPI.addEvent(univerAPI.Event.BeforeCommandExecute, () => {  // custom preprocessing logic before the command is executed})// Example: Destroy the listener after 1 secondsetTimeout(() => {  // Destroy the listener  disposable.dispose()}, 1000)

Execute commands

If you already know the command ID and its parameters, you can execute the command directly with FUniver.executeCommand.

For example, the following code sets the value of cell A1 with the sheet.command.set-range-values command:

TypeScript
const univerAPI = FUniver.newAPI(univer)// Execute the commanduniverAPI.executeCommand('sheet.command.set-range-values', {  value: { v: 'Hello, Univer!' },  range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0 },})

Events API

Univer dispatches events for changes that occur inside a spreadsheet, so an application can listen for them and respond. The events fall into groups such as clipboard operations, selection changes, cell interactions, sheet modifications, and a few others.

Event categories

Full event list: /reference/facade/events

  1. Clipboard Events

    • BeforeClipboardChange: fires before the clipboard content changes; set params.cancel = true to block the change
    • BeforeClipboardPaste: fires before content is pasted; set params.cancel = true to block the paste
    • ClipboardChanged: fires after the clipboard content changes, with the new content
    • ClipboardPasted: fires after content is pasted, with the pasted content
  2. Selection Events

    • SelectionChanged: fires when the selection changes, with the new selection range
    • SelectionMoveStart: fires when the selection starts moving, which allows custom selection effects
    • SelectionMoveEnd: fires when the selection stops moving, with the final range
    • SelectionMoving: fires while the selection moves, which supports live UI updates
    • DragOver: fires while content is dragged over cells
    • Drop: fires when the dragged content is dropped
  3. Cell Events

    • CellClicked: fires when a cell is clicked, with its position and content
    • CellHover: fires when the pointer hovers over a cell, which supports tooltips
    • CellPointerDown: fires when the pointer is pressed on a cell; used to start a drag or a selection
    • CellPointerUp: fires when the pointer is released on a cell; used to finish an operation
    • CellPointerMove: fires when the pointer moves over cells
  4. Sheet Events

    • SheetValueChanged: fires when sheet values change, with the changed range and the new values
    • SheetZoomChanged: fires when the zoom level changes, with the new zoom ratio
    • SheetSkeletonChanged: fires when the sheet structure changes, for example when rows or columns are inserted or deleted
    • BeforeSheetEditStart: fires before cell editing starts; used to control whether editing is allowed
    • SheetEditStarted: fires when cell editing begins; used for custom editor behavior
    • BeforeSheetEditEnd: fires before cell editing ends; used to validate the content
    • SheetEditEnded: fires when cell editing ends, with the edited value
    • SheetEditChanging: fires during cell editing; used for live validation or formatting
    • Scroll: fires when the sheet scrolls, with the scroll position
    • CrosshairHighlightEnabledChanged: fires when crosshair highlight is enabled or disabled
  5. Header Events

    • RowHeaderClick: fires when a row header is clicked
    • RowHeaderHover: fires when the pointer hovers over a row header
    • ColumnHeaderClick: fires when a column header is clicked
    • ColumnHeaderHover: fires when the pointer hovers over a column header
  6. Data Validation Events

    • BeforeSheetDataValidationAdd: fires before a data validation rule is added
    • SheetDataValidationChanged: fires when data validation rules change
    • SheetDataValidatorStatusChanged: fires when the data validation status changes
  7. Comment Events

    • BeforeCommentAdd: fires before a comment is added
    • CommentAdded: fires after a comment is added
    • BeforeCommentUpdate: fires before a comment is updated
    • CommentUpdated: fires after a comment is updated
    • BeforeCommentDeleted: fires before a comment is deleted
    • CommentDeleted: fires after a comment is deleted
  8. Data Processing Events

    • SheetBeforeRangeSort: fires before a range is sorted
    • SheetRangeSorted: fires after a range is sorted
    • SheetBeforeRangeFilter: fires before a range is filtered
    • SheetRangeFiltered: fires after a range is filtered
    • BeforePivotTableAdd: fires before a pivot table is added
    • PivotTableAdded: fires after a pivot table is added

Using events

Call addEvent on univerAPI to register a listener. The pattern is the same for every event:

TypeScript
univerAPI.addEvent(univerAPI.Event.EventName, (params) => {  // Handle event parameters})

Example: listening to cell clicks

TypeScript
univerAPI.addEvent(univerAPI.Event.CellClicked, (params) => {  const { worksheet, workbook, row, column } = params  console.log(`Cell clicked at row ${row}, column ${column}`)})

Example: monitoring clipboard operations

TypeScript
univerAPI.addEvent(univerAPI.Event.BeforeClipboardPaste, (params) => {  const { text, html } = params  // If you want to cancel the clipboard paste  params.cancel = true})

Example: tracking selection changes

TypeScript
univerAPI.addEvent(univerAPI.Event.SelectionChanged, (params) => {  const { worksheet, workbook, selections } = params  console.log('Selection changed:', selections)})

Canceling event listeners

Event listeners return an IDisposable object; use it to remove the listener when it is no longer needed:

TypeScript
const disposable = univerAPI.addEvent(univerAPI.Event.SheetValueChanged, (params) => {  // Handle value changes})// Later, when you want to remove the listener:disposable.dispose()

Best practices

  1. Dispose of event listeners that are no longer needed; otherwise they leak memory.
  2. Choose the event that matches the use case, and prefer a specific event over a general one.
  3. Keep event handlers lightweight, because they run every time the event fires.
  4. To block the default behavior, use BeforeClipboardChange or another "before" event.

Undo and redo

Undo

TypeScript
await univerAPI.undo()

Redo

TypeScript
await univerAPI.redo()

System clipboard

FUniver.copy() and FUniver.paste() read from and write to the system clipboard.

Copy and paste rely on the browser's native API. If the environment or its permissions do not permit them, neither operation works. See the MDN documentation.

The following example copies and pastes a sheet range.

TypeScript
// Prevent failure due to loss of focus when executing copy and paste code in the console,// this example listens for the cell click event and executes the copy and paste code.univerAPI.addEvent(univerAPI.Event.CellClicked, async (params) => {  const fWorkbook = univerAPI.getActiveWorkbook()  const fWorksheet = fWorkbook.getActiveSheet()  // Copy the range A1:B2 to the clipboard  const fRange = fWorksheet.getRange('A1:B2')  fRange.activate().setValues([    [1, 2],    [3, 4],  ])  await univerAPI.copy()  // Paste the copied content to the range C1:D2  const fRange2 = fWorksheet.getRange('C1')  fRange2.activate()  await univerAPI.paste()  // Check the pasted content  console.log(fWorksheet.getRange('C1:D2').getValues()) // [[1, 2], [3, 4]]})

The clipboard commands can also be executed through the command system:

TypeScript
import { CopyCommand, PasteCommand } from '@univerjs/ui'// CopyuniverAPI.executeCommand(CopyCommand.id)// PasteuniverAPI.executeCommand(PasteCommand.id)

UI

To extend the Univer UI, see the following page:

WebSocket

The Facade API provides createSocket. Given a URL, it opens a WebSocket connection. The connection exposes the open, message, close, and error events; messages are sent with the send method, and the connection is closed with the close method.

In a Presets installation, univerAPI.createSocket(url) can be called directly. In a piecemeal installation, install the @univerjs/network package and register UniverNetworkPlugin.

TypeScript
// ... Omits other plugin importsimport { UniverNetworkPlugin } from '@univerjs/network'// ... Omits other facade importsimport '@univerjs/network/facade'// ... Omits other plugin registrationsuniver.registerPlugin(UniverNetworkPlugin)

The following is a minimal example:

TypeScript
// Replace the URL with the address of your own WebSocket serviceconst ws = univerAPI.createSocket('ws://47.100.177.253:8449/ws')ws.open$.subscribe(() => {  console.log('websocket opened')  ws.send('hello')})ws.message$.subscribe((message) => {  console.log('websocket message', message)  const content = JSON.parse(message.data).content  if (!content.includes('command')) {    return  }  const commandInfo = JSON.parse(content)  const { command, options } = commandInfo  const { id, params } = command  // Upon receiving collaborative data, it is locally saved  univerAPI.executeCommand(id, params, options)})ws.close$.subscribe(() => {  console.log('websocket closed')})ws.error$.subscribe((error) => {  console.log('websocket error', error)})univerAPI.addEvent(univerAPI.Event.CommandExecuted, ({ id, type, params, options }) => {  // Only synchronize local mutations  if (    type !== univerAPI.Enum.CommandType.MUTATION ||    options?.fromCollab ||    options?.onlyLocal ||    id === 'doc.mutation.rich-text-editing'  ) {    return  }  const commandInfo = JSON.stringify({ command: { id, type, params }, options: { fromCollab: true } })  ws.send(commandInfo)})

Univer must start with a unitID; collaboration does not work without one.

Register formula

Custom formulas can be registered on the current Univer instance through the Facade API.

The following example calls registerFunction once to register the algorithm, name, and description that a CUSTOMSUM formula requires into the formula plugin. The formula is then available: typing =CUSTOMSUM in any blank cell displays the prompt.

TypeScript
// Registered formulas support lambda functionsconst formulaEngine = univerAPI.getFormula()formulaEngine.registerFunction(  'CUSTOMSUM',  (...variants) => {    let sum = 0    const last = variants[variants.length - 1]    if (last.isLambda && last.isLambda()) {      variants.pop()      const variantsList = variants.map((variant) => (Array.isArray(variant) ? variant[0][0] : variant))      sum += last.executeCustom(...variantsList).getValue()    }    for (const variant of variants) {      sum += Number(variant) || 0    }    return sum  },  'Adds its arguments',)// Use the function in a cellconst fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const cellA1 = fWorksheet.getRange('A1')cellA1.setValue(1)const cellA2 = fWorksheet.getRange('A2')cellA2.setValue(2)const cellA3 = fWorksheet.getRange('A3')cellA3.setValue({ f: '=CUSTOMSUM(A1,A2,LAMBDA(x,y,x*y))' })// A3 will display: 5formulaEngine.calculationEnd((functionsExecutedState) => {  if (functionsExecutedState === 3) {    console.log(cellA3.getValue()) // 5  }})

Call dispose to unregister the formula.

TypeScript
const functionDisposable = formulaEngine.registerFunction({  // calculate})// Unregister the functionfunctionDisposable.dispose()

To provide more complete internationalized content and descriptions, set the locales and description fields as well:

TypeScript
formulaEngine.registerFunction(  'CUSTOMSUM',  (...variants) => {    let sum = 0    const last = variants[variants.length - 1]    if (last.isLambda && last.isLambda()) {      variants.pop()      const variantsList = variants.map((variant) => (Array.isArray(variant) ? variant[0][0] : variant))      sum += last.executeCustom(...variantsList).getValue()    }    for (const variant of variants) {      sum += Number(variant) || 0    }    return sum  },  {    description: {      functionName: 'CUSTOMSUM',      description: 'formulaCustom.CUSTOMSUM.description',      abstract: 'formulaCustom.CUSTOMSUM.abstract',      functionParameter: [        {          name: 'formulaCustom.CUSTOMSUM.functionParameter.number1.name',          detail: 'formulaCustom.CUSTOMSUM.functionParameter.number1.detail',          example: 'A1:A20',          require: 1,          repeat: 0,        },        {          name: 'formulaCustom.CUSTOMSUM.functionParameter.number2.name',          detail: 'formulaCustom.CUSTOMSUM.functionParameter.number2.detail',          example: 'B2:B10',          require: 0,          repeat: 1,        },      ],    },    locales: {      zhCN: {        formulaCustom: {          CUSTOMSUM: {            description: '将单个值、单元格引用或是区域相加,或者将三者的组合相加。',            abstract: '求参数的和',            functionParameter: {              number1: {                name: '数值1',                detail:                  '要相加的第一个数字。 该数字可以是 4 之类的数字,B6 之类的单元格引用或 B2:B8 之类的单元格范围。',              },              number2: {                name: '数值2',                detail: '这是要相加的第二个数字。 可以按照这种方式最多指定 255 个数字。',              },            },          },        },      },      enUS: {        formulaCustom: {          CUSTOMSUM: {            description: `You can add individual values, cell references or ranges or a mix of all three.`,            abstract: `Adds its arguments`,            functionParameter: {              number1: {                name: 'number1',                detail:                  'The first number you want to add. The number can be like 4, a cell reference like B6, or a cell range like B2:B8.',              },              number2: {                name: 'number2',                detail: 'This is the second number you want to add. You can specify up to 255 numbers in this way.',              },            },          },        },      },    },  },)

The options are described below.

  • func holds the algorithm and the name mapping for the formula. Its input is what the user enters when using the formula, which can be a number, a string, a Boolean value, or an array.
  • description sets the description of the custom formula.
  • locales can hold several languages; the naming rules are described in LocaleType. functionList can hold translations for more than one formula. For field details, see the How to add formulas in Formula Engine section.

To reuse the algorithm that the formula system already provides and extend it, register a custom formula through plugin configuration. See Custom Formula for the walkthrough.

Enum API

The Facade API includes the enum types used during development, for example:

TypeScript
console.log(univerAPI.Enum)console.log(univerAPI.Enum.UniverInstanceType.UNIVER_SHEET)console.log(univerAPI.Enum.LifecycleStages.Rendered)

Utility method API

The Facade API also includes a set of utility methods, for example:

TypeScript
console.log(univerAPI.Util)console.log(univerAPI.Util.tools.chatAtABC(10))console.log(univerAPI.Util.tools.ABCatNum('K'))

How is this guide?

© 2026 DreamNum Co., Ltd.