Electron API
The Electron API is the bridge between Trilium's interface and Electron's main process, exposed as the global window.electronApi in the desktop application.
It is not part of the api global of script notes, but frontend scripts running in the desktop application can call it directly. It is undefined in the browser and in the standalone build, so guard calls with if (window.electronApi).
Api
The complete surface exposed to the renderer as window.electronApi via contextBridge. The renderer must access Electron-only functionality through this object — direct require("electron") and @electron/remote are unavailable because nodeIntegration is disabled and contextIsolation is enabled.
The runtime value lives in apps/desktop/src/preload.ts; this interface is the contract both the preload script (satisfies ElectronApi) and the client (window.electronApi) share.
| Property | Description |
|---|---|
window | WindowApi Window chrome, zoom, theme, lifecycle, and main → renderer events. |
clipboard | ClipboardApi System clipboard access beyond what the standard Web Clipboard API offers. |
shell | ShellApi Shell integration — opening URLs, files, and downloads with OS handlers. |
contextMenu | ContextMenuApi Native context-menu plumbing for right-click events on web contents. |
spellcheck | SpellcheckApi Chromium spell checker controls (dictionary, language list). |
systemIntegration | SystemIntegrationApi OS integration — system tray and autostart / launch-on-login. |
printing | PrintingApi Printing and PDF export pipeline. |
navigation | NavigationApi Read/write access to Chromium's back/forward navigation history. |
ws | WsApi In-process bridge that replaces the renderer↔server WebSocket. |
security | SecurityApi Security settings (backend scripting, SQL console) stored outside the DB. |
backupPassphrase | BackupPassphraseApi Write-only access to the backup passphrase, kept in the OS keyring. |
backupLocation | BackupLocationApi The backup folder, which only the main process stores. |
onenote | OneNoteApi OneNote importer sign-in via a loopback OAuth redirect (desktop only). |
nativeExport | NativeExportApi Desktop-native subtree export that streams a .zip straight to a file. |
nativeImport | NativeImportApi Desktop-native large- .zip import that reads the user's file in place via a capability token. |
dialog | DialogApi Native OS pickers that hand the renderer a location the user chose themselves. |
restore | RestoreApi Choosing a backup to restore during setup, read where it lies rather than uploaded. |
transcription | TranscriptionApi Meeting transcription: starting and stopping a recording, and following its state. |
WindowApi
Window-level controls: zoom, theme, title bar, full screen, lifecycle, and a handful of main → renderer event subscriptions.
| Member | Description | ||||
|---|---|---|---|---|---|
setZoomFactor | Sets the page zoom factor for the current window.
| ||||
getZoomFactor | Returns the current page zoom factor ( | ||||
setNativeThemeSource | Overrides the operating system's reported color scheme for this app.
| ||||
setTitleBarOverlay | Customizes the Windows and Linux native title bar overlay (the area containing the minimize / maximize / close buttons).
| ||||
setWindowButtonPosition | Repositions the macOS traffic-light window buttons. Coordinates are relative to the window's top-left corner and given in device-independent pixels: the buttons are drawn by the system rather than by the page, so unlike the surrounding chrome they are unaffected by the page zoom factor and callers have to scale the offsets themselves.
| ||||
onEnterFullScreen | Registers a callback fired whenever the window enters full-screen mode. | ||||
onLeaveFullScreen | Registers a callback fired whenever the window leaves full-screen mode. | ||||
isFullScreen | Synchronously returns whether the window is currently in full-screen mode. | ||||
setFullScreen | Enters or leaves full-screen mode.
| ||||
minimizeWindow | Minimizes the current window to the taskbar / dock. | ||||
maximizeWindow | Maximizes the current window to fill the available screen area. | ||||
unmaximizeWindow | Restores the window from a maximized state to its previous size. | ||||
isMaximized | Synchronously returns whether the window is currently maximized. | ||||
closeWindow | Closes the current window. | ||||
isAlwaysOnTop | Synchronously returns whether the window is pinned above all others. | ||||
setAlwaysOnTop | Pins the window above all others, or unpins it.
| ||||
toggleDevTools | Opens or closes Chromium DevTools for the current window. | ||||
isDevToolsDocked | Synchronously returns whether DevTools is currently open and docked into this window (as opposed to detached into a separate window). | ||||
reloadAllWindows | Triggers a hard reload of every open Trilium window. | ||||
restartApp | Quits the app and immediately relaunches it. | ||||
toggleAllWindows | Shows all hidden windows or hides all visible ones — used by the "show/hide app" global shortcut and tray menu entry. | ||||
clearCache | Clears the underlying Chromium HTTP cache. Resolves once the cache is empty. | ||||
showWindow | Brings the main window to the foreground, restoring it if minimized. | ||||
releaseFirstPaint | Lets the window paint for the first time. The main process holds the first paint of a starting main or extra window, and with it the reveal of the window, until the client has rendered its interface, so that the window never shows a half-built one. No-op for other windows and once released. | ||||
reportStartupMetric | Reports a renderer startup milestone to the main process, which records it relative to OS process creation alongside the main-process startup metrics. Only the first report of each metric is recorded; later reports (e.g. after a window reload or from extra windows) are ignored.
| ||||
onGlobalShortcut | Subscribes to globally registered keyboard shortcuts.
| ||||
onOpenInSameTab | Subscribes to "open note in active tab" requests originating from outside the renderer (e.g. tray menu, deep links).
| ||||
onDevToolsDockChanged | Subscribes to changes of the DevTools docking state. While DevTools is docked, Chromium disables the native window material (Mica / vibrancy).
|
ClipboardApi
Renderer access to the system clipboard for cases the standard Web API can't cover.
| Member | Description | ||||
|---|---|---|---|---|---|
copyImageToClipboard | Writes a raw image (PNG-encoded bytes) to the system clipboard so it can be pasted into other applications as an image rather than as a file.
| ||||
readText | Reads plain text from the system clipboard via the main-process | ||||
readHTML | Reads the HTML flavor of the system clipboard, the same way as |
ShellApi
Wrappers around Electron's shell module for interacting with the OS (default browser, default file handler, downloads, etc.).
Every method here is validated in the main process before dispatch — see apps/server/src/services/shell_validators.ts. The renderer is treated as untrusted: invalid input throws on the main side rather than being silently passed through to electron.shell / WebContents.
| Member | Description | ||||
|---|---|---|---|---|---|
openExternal | Opens a URL in the user's default external browser via Security: the scheme is matched against the allowlist in
| ||||
openPath | Opens a local path with its default OS handler. Security: the path is canonicalized and must resolve to either the Trilium data directory (or a descendant) or the Trilium tmp directory (or a descendant). Anything else — absolute paths elsewhere on disk, traversal attempts, UNC paths that don't normalize under those roots — is rejected. Null bytes, empty strings, and non-existent files are also rejected, and so is a file whose extension makes the OS run it as a program (
Returns | ||||
showItemInFolder | Shows a local file in the OS file manager, with the file itself selected, via Security: the same sandbox as Nothing is reported back: the OS is asked to bring a window forward, and whether it did is not something Electron answers.
| ||||
openFileUrl | Opens a Security: the URL must use the Note: unlike
Returns | ||||
downloadURL | Triggers a Chromium download for the given URL — the file is saved through the normal "Save As" flow instead of being opened in the renderer. Security: locked to the renderer's own origin. The scheme, hostname, and port must all match the running app's origin (
| ||||
openCustom | Shows the operating system's application chooser for a file: the "Open with" dialog on Windows, the desktop portal's chooser on Linux, and on macOS a picker of the applications in Security: the path must resolve to a strict descendant of Trilium's tmp directory and the file must exist on disk. The legitimate caller always passes a path that was just written by
Returns |
ContextMenuApi
Bridge for the native context menu shown over web contents.
| Member | Description | ||||||
|---|---|---|---|---|---|---|---|
onContextMenu | Subscribes to right-click events forwarded from the main process.
| ||||||
webContentsAction | Executes a clipboard / text-input action on the focused web contents.
|
SpellcheckApi
Renderer-side access to Chromium's built-in spell checker.
| Member | Description | ||||
|---|---|---|---|---|---|
addWordToDictionary | Adds a word to the user's personal dictionary so it is no longer flagged. | ||||
getAvailableSpellCheckerLanguages | Returns the BCP-47 language tags Chromium can spell-check on this platform. | ||||
setSpellCheckerLanguages | Applies the spell-check language list to every open window's session immediately, without an application restart. No-op on macOS, where the OS spell checker auto-detects the language.
| ||||
setSpellCheckerEnabled | Enables or disables the built-in spell checker on every open window's session immediately, without an application restart.
|
SystemIntegrationApi
OS integration controls — system tray and autostart / launch-on-login.
| Member | Description |
|---|---|
reloadTray | Rebuilds the tray icon and menu — call after changing tray-related settings. |
reapplyLaunchOnStartup | Re-applies the OS autostart entry after the |
PrintingApi
Printing and PDF export flow. Trilium drives Electron's printing pipeline through a small state machine that the main process owns, with progress and results pushed back to the renderer via IPC events.
| Member | Description | ||||
|---|---|---|---|---|---|
sendPrintProgress | Reports rendering progress from the renderer to the main process.
| ||||
onPrintProgress | Subscribes to progress updates emitted by the main process during a print or PDF export run.
| ||||
onPrintDone | Subscribes to the "print finished" event, fired once the OS print job is dispatched.
| ||||
removePrintListeners | Removes all listeners registered via | ||||
getPrinters | Returns the list of printers known to the OS. | ||||
exportAsPdfPreview | Asks the main process to render the current note as a PDF and return the resulting bytes for the in-app preview. Result is delivered via
| ||||
onExportAsPdfPreviewResult | Subscribes to the result of an
| ||||
removeExportAsPdfPreviewResultListener | Removes the listener registered via | ||||
savePdf | Persists a previously generated PDF buffer to disk via the native save dialog.
| ||||
printFromPreview | Sends the previewed PDF to the OS print dialog with the given options.
|
NavigationApi
Accessors for the underlying Chromium navigation history of the current web contents (back/forward stack), exposed so the renderer can mirror it in custom UI such as the breadcrumb / tab back button.
| Member | Description | ||||
|---|---|---|---|---|---|
clearNavigationHistory | Clears the entire back/forward navigation history. | ||||
navigationCanGoBack | Synchronously returns whether a back navigation is possible. | ||||
navigationCanGoForward | Synchronously returns whether a forward navigation is possible. | ||||
navigationGetAllEntries | Returns every entry in the navigation history, oldest first. | ||||
navigationGetActiveIndex | Returns the index of the currently active entry inside | ||||
navigationLength | Returns the total number of entries in the navigation history. | ||||
navigationGoToIndex | Navigates to the entry at the given index in the history stack.
| ||||
onDidNavigate | Subscribes to top-level navigation events (URL changes that load a new document). | ||||
onDidNavigateInPage | Subscribes to in-page navigation events (hash changes, | ||||
removeDidNavigateListeners | Removes all listeners registered via |
WsApi
In-process replacement for the renderer↔server WebSocket. Backed by Chromium IPC instead of a TCP socket — no port is bound and no auth check is needed because the channel is only reachable from the renderer the BrowserWindow owns. Wire format is whatever the server's MessagingProvider accepts (currently WebSocketMessage / log-error / log-info / ping).
| Member | Description | ||||
|---|---|---|---|---|---|
send | Sends a message from the renderer to the main-process messaging hub.
| ||||
onMessage | Subscribes to messages pushed from the main process.
Returns |
SecurityApi
Security settings that live outside the database (in data_dir/security.json) to prevent malicious scripts from modifying them. Changes require a native OS confirmation dialog and an app restart to take effect.
| Member | Description | ||||
|---|---|---|---|---|---|
setLanAccessEnabled | Requests enabling/disabling LAN access. When enabled, the desktop binds its TCP listener to all interfaces (instead of loopback) so other devices can reach it — e.g. to sync from another device. Same confirmation + restart flow as above.
Returns | ||||
setBackendScriptingEnabled | Requests backend script execution be turned on or off.
| ||||
setSqlConsoleEnabled | Requests the SQL console be turned on or off.
|
BackupPassphraseApi
The backup passphrase, kept encrypted by the OS keyring in a file outside the database (the database is what ends up inside the backup, so a passphrase stored there would ride along inside the very container it protects).
Deliberately write-only: there is no way to read the passphrase back, so a frontend script cannot exfiltrate it. Only the main process ever sees the plaintext again, when it writes a backup.
Both changes are also gated on a native OS confirmation, which a script can request but cannot answer. Without that, a script could quietly swap in a passphrase of its own and every later backup would be encrypted to it.
| Member | Description | ||||
|---|---|---|---|---|---|
getStatus | Whether a passphrase can be stored on this system, and whether one already is. | ||||
set | Stores a passphrase, replacing any existing one, once the user has confirmed it.
| ||||
clear | Forgets the stored passphrase. Existing backups keep the passphrase they were written with. |
BackupLocationApi
The folder that backups are written to. The main process stores it from the folder that the user accepts in the OS dialog, and the options API does not write it, so a frontend script cannot choose where backups go or which folder the backup download reads.
| Member | Description |
|---|---|
choose | Prompts the native folder picker at the current backup folder and, once the user accepts a folder, writes later backups there. |
reset | Writes later backups to the default folder again. |
OneNoteApi
Desktop-only OneNote importer sign-in, driven from the main process via a loopback OAuth redirect.
| Member | Description |
|---|---|
login | Runs the Microsoft delegated-Graph OAuth flow: opens the system browser, captures the redirect on a throwaway loopback server, exchanges the code, and stores the token process-side. Resolves once the desktop session is connected (or with |
NativeExportApi
Desktop-native subtree export that streams a .zip straight to a file.
| Member | Description | ||||
|---|---|---|---|---|---|
exportSubtreeToFile | Prompts a native "save as" dialog, then streams a subtree (branch) export to the chosen path on disk. This bypasses the in-memory download path, so memory stays bounded regardless of archive size. Progress/success/error are reported over the WebSocket via
|
NativeImportApi
Desktop-native import that reads the user's file in place (bounded memory, no temp copy) — the whole point being multi-GB .zip archives, though any importable file is accepted. The renderer never handles a filesystem path: pickFiles runs the OS dialog in the main process and returns opaque capability tokens, which importFromToken redeems. A script can't forge a token or pass a path, so it can never read an arbitrary file.
| Member | Description | ||||
|---|---|---|---|---|---|
pickFiles | Prompts a native "open file" dialog (multi-select, any type) and returns single-use tokens for the chosen files. | ||||
grantDroppedFiles | Resolves files the user dropped onto a drop zone to capability tokens, so a drag-and-drop import takes the same in-place (streamed) path as the dialog. The
| ||||
importFromToken | Imports the file behind a token, with progress/success/error reported over the WebSocket like the HTTP import path.
|
DialogApi
Native OS pickers that hand the renderer a location the user chose themselves.
| Member | Description | ||||
|---|---|---|---|---|---|
pickDirectory | Prompts a native "select folder" dialog. The renderer cannot supply the answer: a script can at most pop the dialog, which the user still has to accept before any path comes back.
| ||||
confirmStartOver | Prompts a native message box before the application restarts into the setup screen, where the user may replace or erase their knowledge base. An OS dialog rather than one of the application's own, for the reason the security toggles use one: a note script can reach every dialog the app draws for itself, and this one guards the path to losing everything. It is never suppressible, so there is no "don't ask again" here. |
RestoreApi
Choosing a backup to restore from the desktop, where the file is already on the same disk as the database it is going to replace and has no business being uploaded to reach it.
Only usable during setup: what it puts forward is restored by the ordinary POST /api/setup/restore/start, which refuses once the application is initialized.
| Member | Description |
|---|---|
pickBackup | Prompts a native "open file" dialog for a |
TranscriptionApi
Meeting transcription, recorded and transcribed on this computer by the main process. The renderer only starts and stops it; the audio never passes through the renderer.
| Member | Description | ||||||||
|---|---|---|---|---|---|---|---|---|---|
isSupported | Whether this build can transcribe on this computer: | ||||||||
start | Starts recording the microphone and the system audio for a meeting note.
Returns | ||||||||
stop | Stops the recording, once the speech already captured has been transcribed. | ||||||||
getState | | ||||||||
renameSpeaker | Names a speaker of a transcript attachment, if a running recording writes that transcript. The recording applies it, so no utterance it writes meanwhile is lost.
Returns | ||||||||
getRecordingsDirectory | Returns the directory that keeps the audio and the transcript as produced of each recording while | ||||||||
onStateChanged | Subscribes to changes of the transcription state, made from any window.
Returns | ||||||||
onLevel | Subscribes to the audio level of the running recording, about four times a second per source.
Returns |
Types
ContextMenuParams
Parameters delivered by the main process to the renderer when the user opens the system context menu (right-click) somewhere inside a web view.
Mirrors the subset of fields from Electron's Electron.ContextMenuParams that the renderer actually consumes when building its custom context menu.
| Property | Description |
|---|---|
x | number Horizontal position of the click, in CSS pixels, relative to the web view. |
y | number Vertical position of the click, in CSS pixels, relative to the web view. |
linkURL | string URL of the link the user clicked on, or an empty string if not on a link. |
linkText | string Visible text of the link the user clicked on, or an empty string. |
mediaType | string Media kind under the cursor (e.g. "none", "image", "video", "audio"). |
isEditable | boolean Whether the element under the cursor is editable (input, textarea, contenteditable). |
selectionText | string Currently selected text, or an empty string if nothing is selected. |
misspelledWord | string The misspelled word under the cursor, or an empty string if none. |
dictionarySuggestions | string[] Spell-check suggestions for misspelledWord, in order of relevance. |
editFlags | { canCut: boolean; canCopy: boolean; canPaste: boolean } Hints about which clipboard operations are currently available. |
BackupPassphraseStatus
What the Options UI needs to know about the stored backup passphrase.
| Property | Description |
|---|---|
available | boolean Whether the OS offers a keyring to keep the passphrase in. Without one it cannot be stored safely, and since unattended backups cannot ask for it, encryption is unavailable altogether. |
set | boolean Whether a passphrase is currently stored. |
BackupPassphraseChange
What became of a request to change the stored backup passphrase.
| Value | Description |
|---|---|
"applied" | The change was confirmed and carried out. |
"cancelled" | The user declined the OS confirmation, so nothing changed. |
"unavailable" | There is no keyring on this system to keep a passphrase in. |
NativeDirectoryPickResult
Outcome of DialogApi.pickDirectory and BackupLocationApi.choose.
| Property | Description |
|---|---|
status | "cancelled" | "selected" |
path optional | string Absolute path of the chosen directory (when status === "selected"). |
OneNoteLoginResult
Outcome of a OneNoteApi.login attempt.
| Property | Description |
|---|---|
connected | boolean True if sign-in completed and a Microsoft Graph token was stored. |
account optional | { name: string; email: string } The connected Microsoft account, present when connected is true. |
error optional | string A human-readable failure reason when connected is false (absent on user cancellation). |
NativeExportResult
Outcome of a NativeExportApi.exportSubtreeToFile request.
| Property | Description |
|---|---|
status | "cancelled" | "saved" | "error" |
filePath optional | string Absolute path the archive was written to (when status === "saved"). |
message optional | string Failure detail (when status === "error"). |
NativeImportPickResult
Outcome of NativeImportApi.pickFiles: capability tokens, never paths.
| Property | Description |
|---|---|
status | "cancelled" | "selected" |
files optional | NativeImportPickedFile[] The user-chosen files (when status === "selected"); one or more, since the dialog allows multi-select. |
NativeImportOptions
Import flags forwarded to the native importer (mirrors the HTTP route's options; no path).
| Property | Description |
|---|---|
safeImport | boolean |
shrinkImages | boolean |
textImportedAsText | boolean |
codeImportedAsCode | boolean |
spreadsheetImportedAsSpreadsheet | boolean |
drawingImportedAsHandwriting | boolean |
explodeArchives | boolean |
replaceUnderscoresWithSpaces | boolean |
NativeImportResult
Outcome of NativeImportApi.importFromToken.
| Property | Description |
|---|---|
status | "error" | "imported" |
importedNoteId optional | string Root note of the import (when status === "imported"). |
message optional | string Failure detail (when status === "error"). |
NativeBackupPickResult
Outcome of RestoreApi.pickBackup: what the chosen backup is, never where it is.
The file itself stays with the main process, which holds it as the one waiting to be restored, so the renderer is given only what the screen has to show and decide with.
| Property | Description |
|---|---|
status | "cancelled" | "error" | "selected" |
fileName optional | string Display name of the chosen backup (when status === "selected"). |
encrypted optional | boolean Whether a passphrase has to be asked for before it can be restored. |
message optional | string Failure detail (when status === "error"), e.g. setup already being busy. |
TranscriptionState
What TranscriptionApi reports to every window.
| Property | Description |
|---|---|
status | "idle" | "starting" | "recording" | "stopping" Phase of the meeting transcription; at most one recording runs at a time. |
noteId | string | null The meeting note the recording belongs to, or null when idle. |
pendingSources | TranscriptSource[] The sources heard speaking, or whose speech is still being transcribed. |
sourceIssues optional | Partial<Record<TranscriptSource, "not_captured" | "no_audio" | "silent">> While recording, the sources whose audio is not being transcribed, and why; absent when every source delivers sound. Why a source's audio is not being transcribed: its capture did not start ( not_captured), it has delivered no audio for 10 s (no_audio), as when its capture hangs, or it has delivered only digital silence for a while (silent), as from a muted device. |
startedAt optional | number When the recording started, in milliseconds since the epoch: set once it records, kept while it stops, absent otherwise. |
error optional | string A problem to tell the user about, sent once with the state it concerns: the recording ended without being stopped, or its transcript cannot be saved. getState() never returns it. |
TranscriptSource
Where an utterance was heard: the local speaker's microphone, or everyone else on the system output.
type TranscriptSource = "microphone" | "system"NativeImportPickedFile
A single user-chosen file: a capability token (redeemed to import it) and its display name — never a path.
| Property | Description |
|---|---|
token | string Single-use, short-lived grant for the chosen file. |
fileName | string Display name of the chosen file. |