Collabora Online editor API reference

LOLeaflet API

Initialization

Usage example


var map = L.map('map', {
    doc: 'file:///path/to/document',
    server: 'wss://localhost',
    documentContainer: 'document-container'
});

Creation

Factory Description
L.map( <HTMLElement|String> id, <Map options> options? ) Instantiates a map object given a div element (or its id) and optionally an object literal with map options described below.

Options

These are the options intended to be used for loleaflet, using any additional options from Leaflet might cause some unexpected behaviour.

Option Type Default Description
doc String undefined Document URL, the server should be able to access the document.
server String undefined The websocket server hosting loolwsd using the ws: protocol. Example: wss://localhost:9980
webserver String undefined The webserver access to hosting loolwsd. Normally it is derived from ‘server’, but can be overridden with an own value in case of proxying. Example: http://localhost:9980
permission String 'view' The document’s permission.
timestamp String undefined A timestamp of the last modification to the document.
documentContainer String / DOM element undefined An outer div, containing the map div, that is used internally for the creation of the toolbar.
toolbarContainer String / DOM element undefined A div used by the default toolbar elements (bold, italic, search, etc.) in loleaflet. If you implement your own toolbar and use controls that do not require a toolbar (like the dialog or scroll control) you can ignore this.
renderingOptions Object undefined Enables the continuous, web view, of the document, see the UNO commands below for this parameter.
print Boolean true Whether the print handler is active (for Chrome).
autoFitWidth Boolean true Whether the document is automatically zoomed so that the width fits the viewing area when the window is resized. The document will not be zoomed in more than map.options.zoom.
zoom Number 10 Default zoom level in which the document will be loaded.
tileWidthTwips Number 3840 Default tile width in twips (how much of the document is covered horizontally in a 256×256 pixels tile). Unless you know what you are doing, this should not be modified; this means twips value for 256 pixels at 96dpi.
tileHeightTwips Number 3840 Default tile height in twips (how much of the document is covered vertically in a 256×256 pixels tile). Unless you know what you are doing, this should not be modified; this means twips value for 256 pixels at 96dpi.
defaultZoom Number 10 The zoom level at which the tile size in twips equals the default size (3840 x 3840). Unless you know what you are doing, this should not be modified.
cursorURL String undefined The path (local to the server) where custom cursor files are stored.

General

General methods for document interaction.

Method Returns Description
search( <String> phrase, <Boolean> backward? ) undefined Searches for the given phrase downward from the current top border of the viewing area. Or backwards if specified.
highlightAll( <String> phrase, undefined Highlights all the occurrences of the given phrase. Please note that this adds an extra layer for the highlights, so it is possible to see both all the highlighted phrase, and the current selection at the same time.
setPermission( <DocumentPermissionValues> documenPermission) undefined Sets the permission of the document.
getDocSize() Point Returns the document size.
getDocType() DocumentTypeValues Returns the document type.
getPageSizes() {twips: [Bounds],
pixels: [Bounds]}
Returns an object describing the size of each page in twips and pixels.
scroll( <Number>x, <Number>y, <ScrollOptions>Options) undefined Scroll right by ‘x’ and down by ‘y’ (or left and up if negative).
scrollDown( <Number>y, <ScrollOptions>Options) undefined Scroll down by ‘y’ (or up if negative).
scrollRight( <Number>x, <ScrollOptions>Options) undefined Scroll right by ‘x’ (or left if negative).
scrollTop( <Number>y, <ScrollOptions>Options) undefined Scroll to ‘y’ offset relative to the beginning of the document.
scrollLeft( <Number>x, <ScrollOptions>Options) undefined Scroll to ‘x’ offset relative to the beginning of the document.
scrollOffset() Point Returns the scroll offset relative to the beginning of the document.
getPreview( <Object>id,
<Number>index,
<Number>maxWidth,
<Number>maxHeight,
<PreviewOptions>options?)
undefined Triggers the creation of a preview with the given id, of maximum maxWidth X maxHeight size, of the page / part with number ‘index’, keeping the original ration.
getCustomPreview( <Object>id,
<Number>part,
<Number>width,
<Number>height,
<Twips>tilePosX,
<Twips>tilePosY,
<Twips>tileWidth,
<Twips>tileHeight,
<PreviewOptions>options?)
undefined Triggers the creation of a preview with the given id, of width X height size, of the [(tilePosX,tilePosY), (tilePosX + tileWidth, tilePosY + tileHeight)] section of the document.
removePreviewUpdate( <Object>id) undfined Cancels the automatic update for the preview defined by ‘id’.
fitWidthZoom( <Number>maxZoom) undfined Zooms in or out so that the document’s width fits the viewing area. The document will not zoom in more than `maxZoom` if the parameter is provided.

ScrollOptions

property type description
update Boolean Whether the update-scroll-offset event is fired.

PreviewOptions

property type description
autoUpdate Boolean Whether a new preview is generated automatically when it becomes invalid.
broadcast Boolean Whether new preview should be broadcasted to other clients of same document.

Toolbar

Toolbar methods.

Method Returns Description
getToolbarCommandValues( <ToolbarCommandValues> unoCommand) Object Returns a JSON mapping of the possible values.
toggleCommandState( <CommandValues> unoCommand) undefined Toggles the state for the given UNO command.
saveAs( <String>url, <String>format?, <String>options?) undefined Save the document as “format” at the given URL by applying the filter options.
downloadAs( <String>name, <String>format?, <String>options?) undefined Download the document as “format” with the name “name” by applying the filter options.
print() undefined Opens the browser’s print dialog or prompts the user to download a PDF version of the document.
cellEnterString( <String>formula) undefined Enters a string of text in the selected cell.
insertFile( <File>file) undefined Insert a file (graphic) in the document.
applyFont( <String>fontName) undefined Applies a font.
applyFontSize( <Number>fontSize) undefined Applies a font size.
applyStyle( <String>style, <String>styleFamily) undefined Applies a style from a style family.
renderFont( <String>fontName) undefined Renders the given font in the smallest rectangle it can fit in.
sendUnoCommand( <String> unoCommand, <Object> param) undefined Sends a uno command with the given parameter to LOKit.

Page oriented

Methods for page oriented documents.

Method Returns Description
getCurrentPageNumber() Number Number of the current page.
getNumberOfPages() Number Total number of pages.
goToPage( <Number>pageNumber) undfined Scrolls to the beginning of the given page.

Part oriented

Methods for page oriented documents.

Method Returns Description
getCurrentPartNumber() Number Number of the current part.
getNumberOfParts() Number Total number of parts.
setPart( <Number>partNumber) undfined Select a specific part.

Events

You can subscribe to the following events using these methods.

Event Data Description
cellformula CellFormulaEvent Fired when the content of the selected cell changes.
commandresult CommandResultEvent Fired when a dispatched uno command or the ‘saveas’ command has finished.
commandstatechanged CommandStateChangedEvent Fired when the state of a command such as .uno:Bold changes.
locontextmenu LOContextMenuEvent Fired when the user’s action invoked a context menu (via a right-click). It contains the structure of the menu.
docsize DocumentSizeEvent Fired when the document size changes.
error ErrorEvent Fired on server or client error.
hyperlinkclicked HyperlinkClickedEvent Fired when the user clicks a hyperlink in the document.
pagenumberchanged PageNumberChangedEvent Fired when the number of pages changes.
print PrintEvent Fired when the URL for the PDF export is ready.
renderfont RenderFontEvent Fired when the font rendering is ready.
search SearchEvent Fired when the search result is ready.
scrollby ScrollByEvent Fired when the document is panned with the keyboard.
scrollto ScrollToEvent Fired when the cursor goes out of the viewing area.
statusindicator StatusIndicator Fired when leaflet is initialized, during document loading or on reconnection.
tilepreview TilePreviewEvent Fired when the rendering of a requested preview is ready.
updateparts UpdatePartsEvent Fired when a new part has been selected.
updatepermission PermissionEvent Fired when the document permission changes.
updatescrolloffset UpdateScrollOffsetEvent Fired when the document is panned and the scrollbars should be moved along with the document.
updatetoolbarcommandvalues UpdateToolbarCommandValuesEvent Fired when the document is loaded and contains the available command values for Font, FontSize, Style, etc.

CellFormulaEvent

property type description
formula String The formula from the selected cell.

CommandResult

property type description
commandName CommandStateChangedValues UNO command or ‘saveas’.
success Boolean or undefined Returns the status code of the command execution, or undefined if the result is not provided, and the command only indicates that the operation has finished.

CommandStateChangedEvent

property type description
commandName CommandStateChangedValues UNO command.
state CommandStateValues UNO command state.

LOContextMenuEvent

property type description
menu String List of the menu entries. The structure looks like:
{ "text": "label text1", "type": "command", "command": ".uno:Something1", "enabled": "true" }, { "text": "label text2", "type": "command", "command": ".uno:Something2", "enabled": "false" }, { "type": "separator" }, { "text": "label text2", "type": "menu", "menu": [ { ... }, { ... }, ... ] }, ...

DocumentSizeEvent

property type description
x Number Document width in pixels.
y Number Document height in pixels.

ErrorEvent

property type description
id Number Identificator of the error that can be used as indication of error message to present to the user.
msg String If present, the error message.
cmd String If present, the server command that caused the error.
kind String If present, the kind of error associated with the command.

The id property of ErrorEvent can have the following values:

value description
1 Internal error. Things still may work to some extent, but the session becomes unreliable.
2 Document couldn’t be loaded.
3 Socket connection error.
4 Socket connection was closed.
5 Document couldn’t be saved.

HyperlinkClickedEvent

property type description
url String Target URL of the hyperlink that the user clicked in the document.

PageNumberChangedEvent

property type description
currentPage Number The current page in the document.
pages Number The number of pages.
docType DocumentTypeValues The document type.
property type description
url String An URL for the PDF exported document.

RenderFontEvent

property type description
font String Font name.
img String The image data URL.

SearchEvent

property type description
originalPhrase String The phrase that has been searched for
count Number Number of search results
results SearchResult[] An array representing the selections of the search results in the document.

ScrollByEvent

property type description
x Number Scroll right by x pixels, or left if negative.
y Number Scroll down by y pixels, or up if negative.

ScrollToEvent

property type description
x Number View’s left border position in pixels.
y Number View’s top border position in pixels.

StatusIndicatorEvent

property type description
statusType StatusIndicatorValues Status type.
value Number If present, a number for 0 to 100 representing the loading status.

TilePreviewEvent

property type description
tile Image The actual preview.
id Object Preview id.
width Number Image width.
height Number Image height.
docType DocumentTypeValues The document type.
part Number If the preview is for a whole part.

UpdatePartsEvent

property type description
selectedPart Number The currently selected part.
parts Number The number of parts in the document.
docType DocumentTypeValues The document type.
partNames String[] If present, an array containing slides’ / spreadsheets’ names.

PermissionEvent

property type description
perm DocumentPermission Document permission.

UpdateScrollOffsetEvent

property type description
x Number Difference in pixels between the document’s left border and view’s left border.
y Number Difference in pixels between the document’s top border and view’s top border.

UpdateToolbarCommandValuesEvent

property type description
commandName ToolbarCommandValues UNO command.
commandValues Object JSON mapping of the possible values.

Object values

A list of possible values for different event object properties.

SearchResult

property type description
part Number The part in which the selection lies.
rectangles Bounds[] Selection bounds in pixels.

DocumentPermissionValues

value type description
'edit' String The document can be edited, dragging is disabled and mouse selection is active.
'view' String The document is in viewing mode, dragging is enabled by default and by clicking in it, editing mode is entered.
'readonly' String The document is in read-only mode, dragging is enabled by default.

CommandStateChangedValues

value type description
'.uno:Bold' String Bold.
'.uno:Italic' String Italic.
'.uno:Underline' String Underline.
'.uno:Strikeout' String Strikeout.
'.uno:LeftPara' String Align left.
'.uno:CenterPara' String Center horizontally.
'.uno:RightPara' String Align right.
'.uno:JustifyPara' String Justified.
'.uno:IncrementIndent' String Increment indent.
'.uno:DecrementIndent' String Decrement indent.
'.uno:StyleApply' String Style related uno command.
'.uno:CharFontName' String Font related uno command.
'.uno:FontHeight' String Font size related uno command.
'.uno:ModifiedStatus' String If the document is now marked as modified. The value is ‘true’ when the document is marked as modified, and ‘false’ the user e.g. undoes all the changes or saves the document.

CommandStateValues

value type description
'true' String For ‘.uno:Bold’, ‘.uno:Italic’, etc.
'false' String For ‘.uno:Bold’, ‘.uno:Italic’, etc.
styleName String For ‘.uno:StyleApply’.
fontName String For ‘.uno:CharFontName’.
fontSize String For ‘.uno:FontHeight’.

DocumentTypeValues

value type description
'text' String Text document, usually handled by Writer.
'presentation' String Text document, usually handled by Impress.
'spreadsheet' String Text document, usually handled by Calc.
'drawing' String Text document, usually handled by Draw.
'other' String Other document type.

StatusIndicatorValues

value type description
'start' String Fired when the progress broadcast is being started.
'setvalue' String Set a value between 0 and 100.
'finish' String The progress is at 100%.
'loleafletloaded' String Fired when the code has been initialized.
'alltilesloaded' String Fired when all empty tiles have been loaded (fired several times).
'initializationcomplete' String Fired when everything that is needed for operating on the document is ready: this._docLayer is defined, statusindicatorfinish was received, .uno:StyleApply was received, .uno:CharFontName was received, and updatepermission was received.

ToolbarCommandValues

value type description
'.uno:StyleApply' String Style related uno command.
'.uno:CharFontName' String Font related uno command.

Object values

A list of common uno commands with their additional parameters.

map.sendUnoCommand('.uno:Bold')
map.sendUnoCommand('.uno:Color',
{
  "Color": {
    "type": "long",
    "value": 16750848
  }
})
command parameter description

PostMessage API

PostMessage API is used to interact with parent frame when loleaflet is enclosed in one. This is useful for hosts wanting to integrate LibreOffice Online in them.

This API is mostly based on WOPI specification with few extensions/modifications. All messages sent are in this form :


{
    "MessageId": "<MessageId>",
    "SendTime": "<Timestamp when message is sent>",
    "Values": {
         "<key>": "<value>"
    }
}

SendTime is the timestamp returned by browsers’ Date.now(). The post messages sent from the WOPI host should also be in same form.

It is to be noted that as mentioned in WOPI specs, loleaflet frame will ignore all post messages coming from the host frame if Host_PostmessageReady has not been received. Further, since for embedding LibreOffice Online as an iframe WOPI implementation is a must, it is required that ‘PostMessageOrigin’ property is present in WOPI host’s CheckFileInfo response. Otherwise, no post messages will be emitted.

Initialization

Editor to WOPI host

MessageId Values Description
App_LoadingStatus Status: <String> DocumentLoadedTime: <Timestamp> If Status is Frame_Ready, loleaflet frame is loaded and UI can be shown.
When Status is Document_Loaded, document has been completely loaded and host can also start sending document-specific query messages using post message API such as Get_Views, Get_Export_Formats etc. DocumentLoadedTime is specified only in this case.

WOPI host to editor

MessageId Values Description
Host_PostmessageReady See WOPI docs for detail.

Query

You can query data from the editor using post message API. All responses are returned with query’s MessageId suffixed with ‘_Resp’ as shown below

Getters
WOPI Host to Editor

MessageId Values Description
Get_Views Queries the editor for currently active views of the document. Response is returned in form of Get_Views_Resp
Get_Export_Formats Queries the editor for all the supported export formats for currently opened document.

Getters response
Editor to WOPI host

MessageId Values Description
Get_Views_Resp ViewId: <Number> UserId: <String> UserName: <String> Color: <Number> Give details of all current views when queried using Get_Views
Get_Export_Formats_Resp Label: <String> Format: <String> Response to query Get_Export_Formats. Label would contain a localised string explaining about the format. Format is the file extension of the format which is required while requesting export of the document.

Session Management

Editor to WOPI Host

MessageId Values Description
View_Added ViewId: <Number> UserId: <String> UserName: <String> Color: <Number> ReadOnly: <Boolean> A new member is added. ViewId is unique integer identifying a session/view. UserId is user identity. UserName is display name of the user. Color is RGB color integer value. ReadOnly tells if the new view is opened as readonly.
View_Removed ViewId: <Number> View with ViewId has closed the document.

Actions

WOPI host to editor

MessageId Values Description
Action_Save DontTerminateEdit: <boolean> DontSaveIfUnmodified: <boolean> Notify: <boolean> Saves the document.
DontTerminateEdit is relevant for spreadsheets where saving a document can terminate the edit mode (text cursor dissappearing). Setting this to true won’t terminate the edit mode and can be used to save document without disrupting user’s editing session in spreadsheets.
DontSaveIfUnmodified prevents loolwsd to save the file back to storage if document is unmodified (only cursor position changed etc.) but still saved. This can be helpful to prevent creating unnecessary file revisions. Notify when present and set to true notifies the host when document is saved. See Action_Save_Resp for details.
Action_SaveAs Filename: <String> Creates copy of the document with given Filename.
Filename is the requested filename for the new file.
Action_Print Prints the document.
Action_Export Format: <String> Downloads the document in format specified by Format. Format must be from the list returned in Get_Export_Formats
Action_ShowBusy Label: <String> Shows an in-progress overlay, just like what appears when saving the doument, with the given Label.
Action_HideBusy Hides any in-progress overlay, if present.

Actions response (WOPI editor to host)

MessageId Values Description
Action_Save_Resp success: <boolean> result: <string> Acknowledgement when save finishes.
success tells if LOOL was able to save the document successfully. When this is false, then another parameter, result is present which contains the reason that document was not saved. In case, document was not saved because it was not modified, then this parameter contains the string ‘unmodified’. In this case, WOPI hosts can be sure that there are no changes pending in the document to be saved to the storage. This response is only emitted if Notify parameter is mentioned by Action_Save PostMessage API.

Miscellaneous

WOPI host to editor

MessageId Values Description
Insert_Button id: <string>
imgurl: <string> hint: <string> mobile: <boolean> label: <string>
Inserts the button to the left of the top toolbar. Only thing that it does is response to click events based on which hosts can act accordingly. It responds with Clicked_Button post message event.
id parameter is a unique id of the toolbar button. It is recommended to prefix such ids given here with some host namespace so that it doesn’t conflict with existing toolbar IDs. In case of conflict, button is not added.
imgurl parameter is the link to the image that will be set as button image in the toolbar. The ideal size of the image is 24x24px. The image must be hosted on the host URL to not violate Content-Security-Policy.
hint This is used as a tooltip of the button.
mobile Whether the button should be shown when the interface switches to mobile mode.
label When a readonly document is opened, we don’t have the toolbar at all. In this case, this newly added button is present in file menubar. The text against this label is used as text of the menubar item.

Editor to WOPI host

MessageId Values Description
Clicked_Button id: <string> This event is emitted when the custom button added via Insert_Button API above is clicked.
UI_SaveAs Requests WOPI host to create appropriate UI, so that the user can choose path and File name for creating a copy of the current file. Response to this query is sent via Action_SaveAs message.