Event handling

Updated at:

Use the ApiEvent mechanism to listen for interactive events in a document, such as file open, save status changes, tab switches, and WebSocket connection status.

Overview

The SDK provides the ApiEvent mechanism for listening to document interactions. When an event fires, ApiEvent runs your registered JavaScript callback functions. Events fall into two categories:

  • Public events: Available across all components (Word, Excel, PPT, PDF).

  • Component events: Specific to a single component, such as Word events or Excel events.

ApiEvent supports binding multiple callback functions to the same event, and unbinding specific functions from registered events.

Important
  • ApiEvent is supported in SDK v1.1.14 and later. For earlier versions, use instance.on or instance.Application.Sub to register events.

  • instance.on and instance.Application.Sub are deprecated and will be removed in a future version. Migrate to ApiEvent.

Usage

All event listeners use AddApiEventListener to register and RemoveApiEventListener to unregister.

// Initialize the SDK instance.
const instance = aliyun.config({
  url: 'The URL for online document preview',
})

await instance.ready()

const handle = (res) => console.log(res)

// Register an event listener.
instance.ApiEvent.AddApiEventListener('tabSwitch', handle)

// Unregister the event listener.
instance.ApiEvent.RemoveApiEventListener('tabSwitch', handle)

Event mechanism in previous versions

In older SDK versions, instance.on and instance.off handle public events, and instance.Application.Sub handles component-level events.

const handle = (res) => console.log(res)

// Register an event listener.
instance.on('tabSwitch', handle)

// Unregister the event listener.
instance.off('tabSwitch', handle)

Public events

Public events work across all components. The following table lists the available public events.

Event name

Description

fileOpen

Fires when the document finishes opening.

error

Fires when an error occurs.

tabSwitch

Fires when the active tab changes.

fileStatus

Fires when the file save status changes.

previewLimit

Fires when the user scrolls to the last page allowed in preview mode.

hasDocMap

Fires to indicate whether the file contains a table of contents.

fullscreenchange

Fires when the document enters or exits full-screen mode.

webSocketStatus

Fires when the WebSocket connection status changes.

fileNameChange

Fires after the file is successfully renamed.

filePasswordStatus

Fires to report the password status of an encrypted file.

ModelVisible

Fires when a modal opens or closes.

OnBroadcast

Fires on a global broadcast, used in multi-user collaboration.

fileOpen

Fires when the document finishes loading. Listen for this event to run initialization logic after the document is ready, or to detect whether the document opened successfully.

Important

Register this event before calling instance.ready(). If this event is not registered before instance.ready(), it may not fire.

Usage

instance.ApiEvent.AddApiEventListener("fileOpen", (data) => {
  console.log("fileOpen: ", data);
});

Success response

Parameter

Type

Description

duration

Number

The time taken to open the document, in milliseconds.

fileInfo

Object

Metadata about the opened file.

fileInfo.createTime

Number

The file creation timestamp (Unix time).

fileInfo.id

String

The file ID.

fileInfo.modifyTime

Number

The last modified timestamp (Unix time).

fileInfo.name

String

The file owner's username.

fileInfo.officeType

String

The file type. For example, s for spreadsheet.

stageTime

Number

The stage loading time, in milliseconds.

success

Boolean

Whether the document opened successfully.

time

Number

The total open time, in milliseconds.

ts

Number

The timestamp when the event fired (Unix time in milliseconds).

{
  duration: 812,
  fileInfo: {
    createTime: 1606461829,
    id: "94749723688",
    modifyTime: 1606461829,
    name: "userName",
    officeType: "s",
  },
  stageTime: 1614,
  success: true,
  time: 1614,
  ts: 1607858260164,
}

Failure response

Parameter

Type

Description

msg

String

The error message.

result

String

The result status. Value: Fail.

{
  msg: "Fail",
  result: "Fail"
}

error

Fires when an error occurs in the document. Listen for this event to display error messages or trigger fallback logic in your application.

Usage

instance.ApiEvent.AddApiEventListener("error", (data) => {
  console.log("error: ", data);
});

Response parameters

Parameter

Type

Description

reason

String

The error message.

{
  reason: "Fail"
}

tabSwitch

Fires when the user switches to a different toolbar tab. Listen for this event to track the active tab or update your UI accordingly.

Usage

instance.ApiEvent.AddApiEventListener("tabSwitch", (data) => {
  console.log("tabSwitch: ", data);
});

Response parameters

Parameter

Type

Description

tabKey

String

The key of the active tab (e.g., "InsertTab", "StartTab"). See each component's tab reference for all possible values.

// Example: Excel
{
  tabKey: "InsertTab",
}

fileStatus

Fires when the file save status changes. Listen for this event to show save indicators in your UI, such as "Saving..." or "All changes saved".

Usage

instance.ApiEvent.AddApiEventListener("fileStatus", (data) => {
  console.log("fileStatus: ", data);
});

Response parameters

Parameter

Type

Description

status

Number

The current save status. Valid values: 0, 1, 2, 3, 4, 5, 6, 7. See the status values below.

Status values:

Value

Description

0

The document has no unsaved changes.

1

The version is saved. Triggered by a manual save, a scheduled save, or closing the browser tab.

2

Saving an empty file is not supported. The file is empty after the kernel saves it.

3

Storage space is full.

4

Save is queued. The server-side save queue is full.

5

Save failed.

6

Save in progress. Triggered by a content change in the document.

7

Save succeeded. The content change was saved successfully.

// Example: check save status in the callback
instance.ApiEvent.AddApiEventListener("fileStatus", (data) => {
  if (data.status === 6) {
    console.log("Saving...");
  } else if (data.status === 7) {
    console.log("All changes saved.");
  } else if (data.status === 5) {
    console.log("Save failed. Please retry.");
  }
});

previewLimit

Fires when the user scrolls to the bottom of the last page allowed in preview mode. Listen for this event to prompt users to purchase access or display a preview-limit message.

Important

This event is only available in page preview mode and supports Word, PPT, and PDF components.

Usage

instance.ApiEvent.AddApiEventListener("previewLimit", (data) => {
  console.log("previewLimit: ", data);
});

Response parameters

Parameter

Type

Applies to

Description

total

Number

Word, PPT, PDF

The page limit.

realTotal

Number

PPT, PDF only

The actual total number of pages. Not available for Word because Word uses a flow layout and cannot determine the exact page count.

// Word document (flow layout — exact page count unavailable)
{
  total: 4,
}

// PPT and PDF
{
  total: 4,
  realTotal: 10,
}

hasDocMap

Fires to indicate whether the document contains a table of contents. Because the Word component retrieves the table of contents using dynamic sharding, listen for this event to determine whether a table of contents is present before displaying navigation UI.

Important

This event is only available for the Word component.

instance.ApiEvent.AddApiEventListener("hasDocMap", (data) => {
  console.log("hasDocMap: ", data);
});

fullscreenchange

Fires when the document enters or exits full-screen mode. Listen for this event to update your application layout when full-screen state changes.

If isBrowserViewFullscreen or isIframeViewFullscreen is set in commonOptions, this event has no effect.

Usage

instance.ApiEvent.AddApiEventListener("fullscreenchange", (data) => {
  console.log("fullscreenchange: ", data);
});

Response parameters

Parameter

Type

Description

status

Number

The full-screen state. Valid values: 0 (exited full-screen mode), 1 (entered full-screen mode).

{
  status: 0, // Exited full-screen mode.
  status: 1, // Entered full-screen mode.
}

webSocketStatus

Fires when the WebSocket connection status changes. Listen for this event to show connection indicators or handle offline scenarios in your application.

Usage

instance.ApiEvent.AddApiEventListener("webSocketStatus", (data) => {
  console.log("webSocketStatus: ", data);
});

Response parameters

Parameter

Type

Description

status

String

The connection status. Valid values: _online, _offline, _close. See the status values below.

Status values:

Value

Description

_online

Connected.

_offline

Offline.

_close

Connection closed.

{
  status: '_online',  // Connected
  status: '_offline', // Offline
  status: '_close',   // Connection closed
}

fileNameChange

Fires after the file is successfully renamed. Listen for this event to update the file name displayed in your application UI.

Usage

instance.ApiEvent.AddApiEventListener("fileNameChange", (data) => {
  console.log("fileNameChange: ", data);
});

Response parameters

Parameter

Type

Description

fileName

String

The new file name.

{
  fileName: "NewName"
}

filePasswordStatus

Fires to report the password status of an encrypted file. Listen for this event to prompt users to enter a password or display an error when an incorrect password is entered.

Important

Register this event before calling instance.ready(). If this event is not registered before instance.ready(), the password prompt will not appear.

Usage

instance.ApiEvent.AddApiEventListener("filePasswordStatus", (data) => {
  console.log("filePasswordStatus: ", data);
});

Response parameters

Parameter

Type

Description

status

String

The password status. Valid values: NeedPassword, InvalidPassword. See the status values below.

Status values:

Value

Description

NeedPassword

A password is required to open the file.

InvalidPassword

The entered password is incorrect.

{
  status: 'NeedPassword',    // A password is required.
  status: 'InvalidPassword', // Incorrect password.
}

ModelVisible

Fires when a modal opens or closes. For example, this event fires when you choose More > Print.

instance.ApiEvent.AddApiEventListener("ModelVisible", (data) => {
  console.log("ModelVisible: ", data);
});

OnBroadcast

Fires on a global broadcast in multi-user collaboration sessions. Listen for this event to synchronize state or display notifications across connected users.

instance.ApiEvent.AddApiEventListener("OnBroadcast", (data) => {
  console.log("OnBroadcast: ", data);
});

Word events

The following table lists the events available for the Word component.

Event name

Description

CurrentPageChange

Fires when the current page number changes.

ClipboardCopy

Fires when content is copied to the clipboard.

DocMapPanelChange

Fires when the outline panel is shown or hidden.

WindowScrollChange

Fires when the document window (not the page) scrolls.

WindowSelectionChange

Fires when the text selection changes.

FontMissing

Fires when a required font is missing.

DocMapItemClick

Fires when the user clicks a heading in the outline.

ControlItemClick

Fires when a content control is clicked.

ContentChange

Fires when the document content changes.

Example

instance.ApiEvent.AddApiEventListener("ClipboardCopy", (data) => {
  console.log("ClipboardCopy: ", data);
});

Excel events

The following table lists the events available for the Excel component.

Event name

Description

Clipboard_Copy

Fires when content is copied to the clipboard.

Worksheet_Activate

Fires when the active worksheet changes.

Worksheet_SelectionChange

Fires when the cell selection changes.

Worksheet_ScrollChange

Fires when the user scrolls the canvas.

Worksheet_ForceLandscape

Fires when forced landscape orientation is applied.

Change

Fires when a cell value is updated.

Example

instance.ApiEvent.AddApiEventListener("Worksheet_Activate", (data) => {
  console.log("Worksheet_Activate: ", data);
});

PPT events

The following table lists the events available for the PPT component.

Event name

Description

SlideShowBegin

Fires when the slideshow enters full-screen playback.

SlideShowEnd

Fires when the slideshow exits full-screen playback.

SlideShowOnNext

Fires on a "next" animation step.

SlideShowOnPrevious

Fires on a "previous" animation step.

SlideSelectionChanged

Fires when the selected slide changes.

ActiveSlideChange

Fires when the user navigates to a different slide.

VideoFullscreenInfo

Fires when a video enters or exits full-screen playback.

TriggerPlayEvent

Fires when an animation is triggered.

SlideMove

Fires when a slide is moved.

PresentationNewSlide

Fires when a new slide is added.

SlideDelete

Fires when a slide is deleted.

SlidePlayerChange

Fires when the playback state changes.

SlideMediaChanged

Fires when the video playback state changes.

SlideLaserPenInkPointsChanged

Fires when ink strokes are drawn with the laser pointer.

SlideInkVisible

Fires to control whether annotations are visible.

SlideInkToolbarVisible

Fires to indicate whether the laser pointer and annotation toolbar are active.

SlideChangeOperator

Fires after the current user adds, moves, or deletes a slide.

Example

instance.ApiEvent.AddApiEventListener("SlideShowBegin", (data) => {
  console.log("SlideShowBegin: ", data);
});

PDF events

The following table lists the events available for the PDF component.

Event name

Description

CurrentPageChange

Fires when the current page number changes.

Scroll

Fires when the document is scrolled.

ZoomUpdated

Fires when the zoom level changes.

StartPlay

Fires when playback starts.

EndPlay

Fires when playback ends.

PicSelectionChange

Fires when the image selection changes.

TextSelectChange

Fires when the text selection changes.

Example

instance.ApiEvent.AddApiEventListener("CurrentPageChange", (data) => {
  console.log("CurrentPageChange: ", data);
});