Frontend API

FrontendApi

The api global available inside frontend script notes (application/javascript;env=frontend).

MemberDescription
$container

JQuery | null
The element a render note's script renders into: the script of a note that a ~renderNote relation points to. It is null for scripts that run any other way.

startNote

FNote
Note where the script execution started — the entry point of the current script bundle (in C terms, the file containing main()). When a script is spread across multiple code notes (descendant code notes loaded as modules via require()), every note in the bundle shares the same startNote, while currentNote differs per note. Messages from api.log() are grouped under this note.

currentNote

FNote
Note containing the source code that is currently executing (in C terms, __FILE__). Equal to startNote unless execution has moved into a descendant module note loaded via require(). Don't confuse this with the note open in the UI — use api.getActiveContextNote() for that.

originEntity

FNote | null
Entity whose event triggered this execution, or null. Most frontend scripts are started by the user or by the UI (startup scripts, widgets), so this is usually null. It is set to a note when: - the script runs through a ~renderNote relation — then it's the note being rendered (the one carrying the relation), not the script note; - a backend script calls api.runOnFrontend() — then it's the backend execution's originEntity, provided that entity was a note.

dayjs

Dayjs
day.js library for date manipulation. See https://day.js.org for documentation

RightPanelWidget

WidgetClass<RightPanelWidget>
Base class for right-panel widgets — class X extends api.RightPanelWidget { … }.

NoteContextAwareWidget

WidgetClass<NoteContextAwareWidget>
Base class for note-context-aware widgets — class X extends api.NoteContextAwareWidget { … }.

BasicWidget

WidgetClass<BasicWidget>
Base class for basic widgets — class X extends api.BasicWidget { … }.

activateNote
activateNote(notePath: string): Promise<void>

Activates note in the tree and in the note detail.

ParameterDescription
notePathstring
(or noteId)
activateNewNote
activateNewNote(notePath: string): Promise<void>

Activates newly created note. Compared to this.activateNote() also makes sure that frontend has been fully synced.

ParameterDescription
notePathstring
(or noteId)
openTabWithNote
openTabWithNote(notePath: string, activate: boolean): Promise<void>

Open a note in a new tab.

ParameterDescription
notePathstring
(or noteId)
activateboolean
set to true to activate the new tab, false to stay on the current tab
openSplitWithNote
openSplitWithNote(notePath: string, activate: boolean): Promise<void>

Open a note in a new split.

ParameterDescription
notePathstring
(or noteId)
activateboolean
set to true to activate the new split, false to stay on the current split
runOnBackend
runOnBackend(func: Func, params?: unknown[]): Promise<unknown>

Executes given anonymous function on the backend. Internally this serializes the anonymous function into string and sends it to backend via AJAX. Please make sure that the supplied function is synchronous. Only sync functions will work correctly with transaction management. If you really know what you're doing, you can call api.runAsyncOnBackendWithManualTransactionHandling()

ParameterDescription
funcFunc
(synchronous) function to be executed on the backend
params
optional
unknown[]
list of parameters to the anonymous function to be sent to backend

Returns Promise<unknown>: return value of the executed function on the backend

runAsyncOnBackendWithManualTransactionHandling
runAsyncOnBackendWithManualTransactionHandling(func: Func, params?: unknown[]): Promise<unknown>

Executes given anonymous function on the backend. Internally this serializes the anonymous function into string and sends it to backend via AJAX. This function is meant for advanced needs where an async function is necessary. In this case, the automatic request-scoped transaction management is not applied, and you need to manually define transaction via api.transactional().

If you have a synchronous function, please use api.runOnBackend().

ParameterDescription
funcFunc
(synchronous) function to be executed on the backend
params
optional
unknown[]
list of parameters to the anonymous function to be sent to backend

Returns Promise<unknown>: return value of the executed function on the backend

isBackendScriptingEnabled
isBackendScriptingEnabled(): boolean

Whether backend script execution is enabled on the server (the [Security] backendScriptingEnabled config toggle). When it's disabled, api.runOnBackend() / api.runAsyncOnBackendWithManualTransactionHandling() reject with a "Backend script execution is disabled" error, so check this first to let a script degrade gracefully instead of throwing.

isSqlConsoleEnabled
isSqlConsoleEnabled(): boolean

Whether the SQL console is enabled on the server (the [Security] sqlConsoleEnabled config toggle). When it's disabled, backend scripts that run raw SQL (api.sql.*) fail, so check this before invoking SQL-backed logic via api.runOnBackend().

searchForNotes
searchForNotes(searchString: string): Promise<FNote[]>

This is a powerful search method - you can search by attributes and their values, e.g.: "#dateModified =* MONTH AND #log". See full documentation for all options at: https://triliumnext.github.io/Docs/Wiki/search.html

searchForNote
searchForNote(searchString: string): Promise<FNote | null>

This is a powerful search method - you can search by attributes and their values, e.g.: "#dateModified =* MONTH AND #log". See full documentation for all options at: https://triliumnext.github.io/Docs/Wiki/search.html

getNote
getNote(noteId: string): Promise<FNote | null>

Returns note by given noteId. If note is missing from the cache, it's loaded.

getNotes
getNotes(noteIds: string[], silentNotFoundError?: boolean): Promise<FNote[]>

Returns list of notes. If note is missing from the cache, it's loaded.

This is often used to bulk-fill the cache with notes which would have to be picked one by one otherwise (by e.g. createLink())

ParameterDescription
noteIdsstring[]
silentNotFoundError
optional
boolean
don't report error if the note is not found
reloadNotes
reloadNotes(noteIds: string[]): Promise<void>

Update frontend tree (note) cache from the backend.

createNote
createNote(parentNotePath: string, opts?: CreateNoteOpts): Promise<{ note: FNote | null; branch: FBranch | undefined }>

Creates a new note as a child of the given parent, entirely on the frontend — no backend scripting required (unlike api.runOnBackend(() => api.createTextNote(...))). By default the new note is activated in the current tab with its title focused for editing; pass { activate: false } to create it silently.

ParameterDescription
parentNotePathstring
note path (or noteId) of the parent under which to create the note
opts
optional
CreateNoteOpts
creation options — e.g. { title, content, type, mime, activate }

Returns Promise<{ note: FNote | null; branch: FBranch | undefined }>: the created note and its branch, resolved from the frontend cache

getInstanceName
getInstanceName(): string | null

Instance name identifies particular Trilium instance. It can be useful for scripts if some action needs to happen on only one specific instance.

addTextToActiveContextEditor
addTextToActiveContextEditor(text: string): void

Adds given text to the editor cursor

ParameterDescription
textstring
this must be clear text, HTML is not supported.
getActiveContextNote
getActiveContextNote(): FNote

Returns FNote: active note (loaded into center pane)

getActiveContext
getActiveContext(): NoteContext

Obtains the currently active/focused split in the current tab.

Note that this method does not return the note context of the "Quick edit" panel, it will return the note context behind it.

getActiveMainContext
getActiveMainContext(): NoteContext

Obtains the main context of the current tab. This is the left-most split.

Note that this method does not return the note context of the "Quick edit" panel, it will return the note context behind it.

getNoteContexts
getNoteContexts(): NoteContext[]

Returns NoteContext[]: returns all note contexts (splits) in all tabs

getMainNoteContexts
getMainNoteContexts(): NoteContext[]

Returns NoteContext[]: returns all main contexts representing tabs

getActiveContextTextEditor
getActiveContextTextEditor(): Promise<TextEditor | null>

Returns the editor of the text note in the active tab or split. Resolves to null if it shows no editable text note within 200 ms, and throws an error when no tab is active.

getActiveContextCodeEditor
getActiveContextCodeEditor(): Promise<CodeEditor | null>

Returns the editor of the code note in the active tab or split. Resolves to null if it shows no code editor within 200 ms, and throws an error when no tab is active.

getActiveNoteDetailWidget
getActiveNoteDetailWidget(): Promise<unknown>

Get access to the widget handling note detail. Methods like getWidgetType() and getTypeWidget() to get to the implementation of actual widget type.

getActiveContextNotePath
getActiveContextNotePath(): string | null

Returns string | null: returns a note path of active note or null if there isn't active note

getComponentByEl
getComponentByEl(el: HTMLElement): unknown

Returns component which owns the given DOM element (the nearest parent component in DOM tree)

ParameterDescription
elHTMLElement
DOM element
showMessage
showMessage(message: string, delay?: number): void

Show an info toast message to the user.

showError
showError(message: string, delay?: number): void

Show an error toast message to the user.

showInfoDialog
showInfoDialog(message: string): Promise<void>

Show an info dialog to the user.

showConfirmDialog
showConfirmDialog(message: string): Promise<boolean>

Show confirm dialog to the user.

Returns Promise<boolean>: promise resolving to true if the user confirmed

showPromptDialog
showPromptDialog(props: { title?: string; message?: string; defaultValue?: string }): Promise<string | null>

Show prompt dialog to the user.

Returns Promise<string | null>: promise resolving to the answer provided by the user

pickSingleItem
pickSingleItem(props: { title?: string; items: PickerItem[] | PickerItemGroup[]; placeholder?: string }): Promise<PickerItem | null>

Show a dialog for picking one item out of many, grouped and searchable.

items are either the items themselves or groups of them, never the two mixed. Named for the one thing it does now: picking several at once will be a method of its own beside this.

Returns Promise<PickerItem | null>: promise resolving to the item picked, or null where the user backed out.

createLink
createLink(notePath: string, params?: LinkOptions): Promise<JQuery>

Create a note link (jQuery object) for given note.

ParameterDescription
notePathstring
(or noteId)
params
optional
LinkOptions

Returns Promise<JQuery>: - jQuery element with the link (wrapped in )

createNoteLink
createNoteLink(notePath: string, params?: LinkOptions): Promise<JQuery>
triggerCommand
triggerCommand(name: string, data?: Record<string, unknown>): Promise<unknown>

Trigger command. This is a very low-level API which should be avoided if possible.

triggerEvent
triggerEvent(name: string, data?: Record<string, unknown>): Promise<unknown>

Trigger event. This is a very low-level API which should be avoided if possible.

setupElementTooltip
setupElementTooltip(el: JQuery): void

Shows a preview of the linked note while the mouse pointer rests on the element, as Trilium does for links in note content. The element must be a link whose href or data-href points to a note, such as #root/abc123.

ParameterDescription
elJQuery
The link, as a jQuery object.
protectNote
protectNote(noteId: string, protect: boolean): Promise<void>
ParameterDescription
noteIdstring
protectboolean
true to protect note, false to unprotect
protectSubTree
protectSubTree(noteId: string, protect: boolean): Promise<void>
ParameterDescription
noteIdstring
protectboolean
true to protect subtree, false to unprotect
getTodayNote
getTodayNote(): Promise<FNote>

Returns date-note for today. If it doesn't exist, it is automatically created.

getDayNote
getDayNote(date: string): Promise<FNote>

Returns day note for a given date. If it doesn't exist, it is automatically created.

ParameterDescription
datestring
e.g. "2019-04-29"
getWeekFirstDayNote
getWeekFirstDayNote(date: string): Promise<FNote>

Returns day note for the first date of the week of the given date. If it doesn't exist, it is automatically created.

ParameterDescription
datestring
e.g. "2019-04-29"
getWeekNote
getWeekNote(date: string): Promise<FNote>

Returns week note for given date. If such a note doesn't exist, it is automatically created.

ParameterDescription
datestring
in YYYY-MM-DD format
getMonthNote
getMonthNote(month: string): Promise<FNote>

Returns month-note. If it doesn't exist, it is automatically created.

ParameterDescription
monthstring
e.g. "2019-04"
getQuarterNote
getQuarterNote(date: string): Promise<FNote>

Returns quarter note for given date. If such a note doesn't exist, it is automatically created.

ParameterDescription
datestring
in YYYY-MM format
getYearNote
getYearNote(year: string): Promise<FNote>

Returns year-note. If it doesn't exist, it is automatically created.

ParameterDescription
yearstring
e.g. "2019"
setHoistedNoteId
setHoistedNoteId(noteId: string): void

Hoist note in the current tab. See https://triliumnext.github.io/Docs/Wiki/note-hoisting.html

ParameterDescription
noteIdstring
set hoisted note. 'root' will effectively unhoist
bindGlobalShortcut
bindGlobalShortcut(keyboardShortcut: string, handler: () => void, namespace?: string): void
ParameterDescription
keyboardShortcutstring
e.g. "ctrl+shift+a"
handler() => void
namespace
optional
string
specify namespace of the handler for the cases where call for bind may be repeated. If a handler with this ID exists, it's replaced by the new handler.
waitUntilSynced
waitUntilSynced(): Promise<unknown>

Trilium runs in a backend and frontend process, when something is changed on the backend from a script, frontend will get asynchronously synchronized.

This method returns a promise which resolves once all the backend -> frontend synchronization is finished. Typical use case is when a new note has been created, we should wait until it is synced into frontend and only then activate it.

refreshIncludedNote
refreshIncludedNote(includedNoteId: string): void

This will refresh all currently opened notes which have included note specified in the parameter

ParameterDescription
includedNoteIdstring
noteId of the included note
randomString
randomString(length: number): string

Return randomly generated string of given length. This random string generation is NOT cryptographically secure.

ParameterDescription
lengthnumber
of the string

Returns string: random string

formatSize
formatSize(size: number): string
ParameterDescription
sizenumber
in bytes

Returns string: formatted string

formatNoteSize
formatNoteSize(size: number): string
ParameterDescription
sizenumber
in bytes

Returns string: formatted string

htmlToMarkdown
htmlToMarkdown(html: string): Promise<string>

Converts the given HTML string to Markdown.

Unlike the backend API, this runs on the server (the HTML→Markdown converter is backend-only), so it returns a promise.

ParameterDescription
htmlstring
HTML content to convert

Returns Promise<string>: Markdown representation of the input HTML

markdownToHtml
markdownToHtml(markdown: string): Promise<string>

Converts the given Markdown string to HTML.

Runs entirely in the browser; the promise is only needed because the Markdown renderer is loaded on demand.

ParameterDescription
markdownstring
Markdown content to convert

Returns Promise<string>: HTML representation of the input Markdown

formatDateISO
formatDateISO(date: Date): string

Returns string: date in YYYY-MM-DD format

parseDate
parseDate(str: string): Date

Parses a date string into a Date.

logMessages

Record<string, string[]>
Per-note log message buffers shown in the UI log pane.

logSpacedUpdates

Record<string, unknown>
Per-note spaced-update handlers for the log pane.

log
log(...args: unknown[]): void

Log given message to the log pane in UI. Accepts multiple arguments which are joined with spaces, similar to console.log.

preact

Preact
The Preact API surface (components, hooks) for render scripts.

FNote

A note as seen by frontend scripts (subset of the client's FNote).

MemberDescription
noteId

string
The ID of the note.

title

string
The title of the note. For a protected note, it is [protected] until a protected session is started.

type

string
The note type, such as text, code, file, image, search, book, render or launcher.

mime

string
The MIME type of the note's content, such as application/json.

isProtected

boolean
Whether the note is protected (encrypted).

isArchived

boolean
Whether the note is archived (has the archived label).

isMetadataReadOnly

boolean
Whether the note's title and icon cannot be edited, which is the case for the system notes behind the options, the in-app help and the launch bar configuration.

attributes

string[]
IDs of this note's owned attributes.

targetRelations

string[]
IDs of relations pointing at this note.

parents

string[]
Parent note IDs.

children

string[]
Child note IDs.

getParentNotes
getParentNotes(): FNote[]

Returns the parent notes that the client has already loaded. A parent that is not loaded is skipped, and a search note that shows this note in its results counts as a parent.

getChildNotes
getChildNotes(): Promise<FNote[]>

Loads any missing child notes from the server, then returns all child notes in tree order. Archived children are included.

getParentNoteIds
getParentNoteIds(): string[]

Returns the IDs of the parent notes. The returned array is the note's own list, so do not change it.

getChildNoteIds
getChildNoteIds(): string[]

Returns the IDs of the child notes in tree order, archived ones included. The returned array is the note's own list, so do not change it.

getChildNoteIdsWithArchiveFiltering
getChildNoteIdsWithArchiveFiltering(includeArchived?: boolean): Promise<string[]>

Returns the IDs of the child notes in tree order, leaving out archived notes unless includeArchived is true. Leaving out archived notes takes a search on the server; for a search note or a note in the hidden subtree, all children are returned.

ParameterDescription
includeArchived
optional
boolean
whether to keep archived children. Defaults to false.
getSubtreeNotes
getSubtreeNotes(): Promise<FNote[]>

Returns all descendants of the note, loading missing ones from the server one level at a time. An archived note and everything below it are left out, and the note itself is not included.

getSubtreeNoteIds
getSubtreeNoteIds(includeArchived?: boolean): Promise<string[]>

Returns the IDs of all the note's descendants, depth-first, without the note itself. Archived notes and the notes below them are left out unless includeArchived is true.

hasChildren
hasChildren(): boolean

Returns true if the note has at least one child, archived ones included. For a search note, the results count as children only once they are loaded.

hasAncestor
hasAncestor(ancestorNoteId: string, followTemplates?: boolean): boolean

Returns true if the note with the given ID is this note or one of its ancestors. It walks only parents the client has already loaded.

ParameterDescription
ancestorNoteIdstring
followTemplates
optional
boolean
whether to also walk up from the notes this note takes attributes from through ~template and ~inherit relations. Defaults to false.
isRoot
isRoot(): boolean

Returns true if this is the root note of the tree.

getParentBranchIds
getParentBranchIds(): string[]

Returns the IDs of the branches that place this note under each of its parents.

getBranchIds
getBranchIds(): string[]

Returns the IDs of the branches that place the note under its parents.

getParentBranches
getParentBranches(): FBranch[]

Returns the branches that place this note under each of its parents. A branch the client has not loaded is skipped.

getChildBranches
getChildBranches(): FBranch[]

Returns the branches to this note's children, in tree order. A branch the client has not loaded is skipped.

getBranches
getBranches(): FBranch[]

Returns the branches that place the note under its parents.

getFilteredChildBranches
getFilteredChildBranches(): FBranch[]

Returns the same branches as getChildBranches(). Despite the name, archived children are not filtered out.

getAllNotePaths
getAllNotePaths(): string[][]

Returns every path from the root to the note, each as a list of note IDs that starts with root. Paths that pass through a search note are left out.

getBestNotePath
getBestNotePath(hoistedNoteId?: string, activeNotePath?: string | null): string[]

Returns the note's best path as a list of note IDs that starts with root. Paths inside the hoisted note's subtree come first, then paths without archived or hidden notes; among equal paths, the one sharing the longest start with activeNotePath wins, then the shortest.

ParameterDescription
hoistedNoteId
optional
string
The hoisted note, root by default.
activeNotePath
optional
string | null
The path of the active note, as note IDs joined by /.
getBestNotePathString
getBestNotePathString(hoistedNoteId?: string): string

Returns the note's best path, as getBestNotePath() chooses it, as note IDs joined by /, such as root/a1h315/js725h.

ParameterDescription
hoistedNoteId
optional
string
The hoisted note, root by default.
getSortedNotePathRecords
getSortedNotePathRecords(hoistedNoteId?: string, activeNotePath?: string | null): NotePathRecord[]

Returns every path from the root to this note, best first. Paths inside the hoisted note come first, then paths that do not pass through an archived note or the hidden subtree, then paths that share the most with activeNotePath, then shorter paths. Paths through search notes are left out, and only parents the client has loaded are followed.

ParameterDescription
hoistedNoteId
optional
string
the ID of the hoisted note. Defaults to root.
activeNotePath
optional
string | null
a note path such as root/abc123/def456, used to prefer paths close to it.
getAttributes
getAttributes(type?: string, name?: string): Attribute[]

Returns the note's attributes, including inherited ones, optionally only those of the given type and name. The note's own attributes come first, then the ones inherited from its parents, then the ones from its templates.

ParameterDescription
type
optional
string
label or relation; any other value throws an error.
name
optional
string
The attribute name, without the # or ~ prefix.
getOwnedAttributes
getOwnedAttributes(type?: string, name?: string): Attribute[]

Returns the note's own attributes, without inherited ones, optionally only those of the given type and name.

ParameterDescription
type
optional
string
label or relation; any other value throws an error.
name
optional
string
The attribute name, without the # or ~ prefix.
getAttribute
getAttribute(type: string, name: string): Attribute | null

Returns the first attribute of the given type and name, including inherited ones, or undefined if the note has none.

ParameterDescription
typestring
label or relation.
namestring
getOwnedAttribute
getOwnedAttribute(type: string, name: string): Attribute | null

Returns the first of the note's own attributes with the given type and name, or undefined if the note has none.

ParameterDescription
typestring
label or relation.
namestring
getAttributeValue
getAttributeValue(type: string, name: string): string | null

Returns the value of the first attribute of the given type and name, including inherited ones, or null if the note has none.

ParameterDescription
typestring
label or relation.
namestring
getOwnedAttributeValue
getOwnedAttributeValue(type: string, name: string): string | null

Returns the value of the first of the note's own attributes with the given type and name, or null if the note has none.

ParameterDescription
typestring
label or relation.
namestring
hasAttribute
hasAttribute(type: string, name: string): boolean

Returns whether the note has an attribute of the given type and name, including inherited ones.

ParameterDescription
typestring
label or relation.
namestring
hasOwnedAttribute
hasOwnedAttribute(type: string, name: string): boolean

Returns whether the note itself has an attribute of the given type and name, without inherited ones.

ParameterDescription
typestring
label or relation.
namestring
getAttributeDefinitions
getAttributeDefinitions(): Attribute[]

Returns the attribute definitions that apply to the note, at most one per defined name. When the note gets a definition from several places, such as its own, an ancestor's and a template's, the nearest one wins, in the order getAttributes() lists them.

getPromotedDefinitionAttributes
getPromotedDefinitionAttributes(): Attribute[]

Returns the attribute definitions that are marked as promoted, at most one per name, grouped by the note that owns them and ordered by position. Returns an empty array if the note has a truthy hidePromotedAttributes label.

getLabels
getLabels(name?: string): Attribute[]

Returns the note's labels, including inherited ones, optionally only those with name.

getOwnedLabels
getOwnedLabels(name?: string): Attribute[]

Returns the note's own labels, without inherited ones, optionally only those with name.

getLabel
getLabel(name: string): Attribute | null

Returns the first label with the given name, including inherited ones, or undefined if the note has none.

getOwnedLabel
getOwnedLabel(name: string): Attribute | null

Returns the first of the note's own labels with the given name, or undefined if the note has none.

getLabelValue
getLabelValue(name: string): string | null

Returns the value of the first label with the given name, including inherited ones, or null if the note has none.

getOwnedLabelValue
getOwnedLabelValue(name: string): string | null

Returns the value of the first of the note's own labels with the given name, or null if the note has none.

hasLabel
hasLabel(name: string): boolean

Returns whether the note has a label with the given name, including inherited ones.

hasOwnedLabel
hasOwnedLabel(name: string): boolean

Returns whether the note itself has a label with the given name, without inherited ones.

hasLabelOrDisabled
hasLabelOrDisabled(name: string): boolean

Returns whether the note has a label with the given name, including inherited ones, or the same label with the disabled: prefix, which a safe import gives it.

isLabelTruthy
isLabelTruthy(name: string): boolean

Returns whether the note has a label with the given name, including inherited ones, whose value is anything but false. A label without a value counts as true.

getRelations
getRelations(name?: string): Attribute[]

Returns the note's relations, including inherited ones, optionally only those with name.

getOwnedRelations
getOwnedRelations(name: string): Attribute[]

Returns the note's own relations, without inherited ones, optionally only those with name.

getRelation
getRelation(name: string): Attribute | null

Returns the first relation with the given name, including inherited ones, or undefined if the note has none.

getOwnedRelation
getOwnedRelation(name: string): Attribute | null

Returns the first of the note's own relations with the given name, or undefined if the note has none.

getRelationValue
getRelationValue(name: string): string | null

Returns the target note ID of the first relation with the given name, including inherited ones, or null if the note has none.

getOwnedRelationValue
getOwnedRelationValue(name: string): string | null

Returns the target note ID of the first of the note's own relations with the given name, or null if the note has none.

hasRelation
hasRelation(name: string): boolean

Returns whether the note has a relation with the given name, including inherited ones.

hasOwnedRelation
hasOwnedRelation(name: string): boolean

Returns whether the note itself has a relation with the given name, without inherited ones.

getLabelOrRelation
getLabelOrRelation(nameWithPrefix: string): string | null

Returns the value of a label or relation, inherited ones included, or null if the note has none. A relation's value is the ID of its target note.

ParameterDescription
nameWithPrefixstring
the attribute name prefixed with # for a label or ~ for a relation. A name without a prefix is looked up as a label.
getRelationTarget
getRelationTarget(name: string): Promise<FNote | null>

Returns the target note of the first relation with the given name, including inherited ones. Returns null if the note has no such relation, the relation has no target, or the target note does not exist.

getRelationTargets
getRelationTargets(name: string): Promise<(FNote | null)[]>

Returns the target notes of the note's relations with the given name, including inherited ones, in the order of the relations. A relation whose target is missing gives null.

getTargetRelations
getTargetRelations(): Attribute[]

Returns the relations, owned by any note, that point at this note.

getTargetRelationSourceNotes
getTargetRelationSourceNotes(): Promise<FNote[]>

Returns the notes that own a relation pointing at this note.

getContent
getContent(): Promise<string | Uint8Array<ArrayBufferLike>>

Fetches the note's content from the server. Resolves to a string for text-based notes; for a binary note such as an image or file, the content is not sent, and for a protected note without a protected session, it is an empty string.

getJsonContent
getJsonContent(): Promise<unknown>

Fetches the note's content and parses it as JSON. Resolves to null if the content is empty, is not a string, or is not valid JSON.

getBlob
getBlob(): Promise<Blob | null>

Fetches the note's content together with its blob ID, length and modification date. Resolves to null if the request fails.

getNoteComplement
getNoteComplement(): Promise<Blob | null>

Returns the blob that holds the note's content.

getMetadata
getMetadata(): Promise<NoteMetadata>

Returns the note's creation and modification dates, which it requests from the server.

attachments

Attachment[] | null
The note's attachments, or null until getAttachments() loads them. Use getAttachments() instead of reading this property.

getAttachments
getAttachments(): Promise<Attachment[]>

Returns the note's attachments. The first call loads them from the server, and later calls reuse that list.

getAttachmentsByRole
getAttachmentsByRole(role: string): Promise<Attachment[]>

Returns the note's attachments with the given role, such as image or file.

getAttachmentById
getAttachmentById(attachmentId: string): Promise<Attachment | undefined>

Returns the note's attachment with the given ID, or undefined if this note has no such attachment.

getNotesToInheritAttributesFrom
getNotesToInheritAttributesFrom(): FNote[]

Returns the target notes of this note's ~template and ~inherit relations, inherited relations included. A target note that the client has not loaded appears as undefined.

getIcon
getIcon(): string

Returns the CSS classes of the note's icon, such as tn-icon bx bx-note. The icon comes from the iconClass label, then the workspaceIconClass label, then a default for the note type.

isFolder
isFolder(): boolean

Returns true if the note shows as a folder in the tree: a search note, or a note with children (archived ones included). Always false when the note has a truthy subtreeHidden label.

isShared
isShared(): boolean

Returns true if the note is placed, directly or through ancestors the client has loaded, under the shared notes root (_share).

isContentAvailable
isContentAvailable(): boolean

Returns true if the note's content can be read: the note is not protected, or a protected session is active.

isJson
isJson(): boolean

Returns true if the note's MIME type is application/json.

isJavaScript
isJavaScript(): boolean

Returns whether the note is a code, file or launcher note with a JavaScript MIME type.

isJsx
isJsx(): boolean

Returns true if the note is a code note with the MIME type text/jsx.

isHtml
isHtml(): boolean

Returns whether the note is a code, file or render note with the text/html MIME type.

isMarkdown
isMarkdown(): boolean

Returns true if the note is a code note with a Markdown MIME type (text/markdown, text/x-markdown or text/x-gfm).

isOptions
isOptions(): boolean

Returns true if the note is one of Trilium's settings pages.

isTriliumScript
isTriliumScript(): boolean

Returns true if the note's MIME type starts with application/javascript, which covers both frontend and backend scripts. The note type is not checked.

isTriliumSqlite
isTriliumSqlite(): boolean

Returns true if the note is a SQL console note, which has the MIME type text/x-sqlite;schema=trilium.

isLaunchBarConfig
isLaunchBarConfig(): boolean

Returns true if the note is a launcher or one of the notes that hold the launch bar's launchers.

isHiddenCompletely
isHiddenCompletely(): boolean

Returns whether every path to the note runs through the hidden subtree, so that no clone of it appears in the visible tree. Paths through search notes are not counted.

isInHiddenSubtree
isInHiddenSubtree(): boolean

Returns true if the note is the hidden subtree's root (_hidden) or has it as an ancestor through any of its loaded parents, even when the note is also cloned into the visible tree.

isEligibleForConversionToAttachment
isEligibleForConversionToAttachment(): boolean

Returns true if the image note can be converted into an attachment of its parent: it is an image note without children, it has exactly one parent, that parent is a text note, the content of both is available, and no note other than the parent links to the image.

getColorClass
getColorClass(): string

Returns the CSS class that applies the note's color label, such as color-ff0000, or an empty string if the label is missing or not a valid color. The first call for a color adds the class's style rule to the page.

getCssClass
getCssClass(): string

Returns the values of all the note's cssClass labels, inherited ones included, separated by spaces.

getWorkspaceIconClass
getWorkspaceIconClass(): string

Returns the value of the note's workspaceIconClass label, or an empty string if it has none.

getWorkspaceTabBackgroundColor
getWorkspaceTabBackgroundColor(): string

Returns the value of the note's workspaceTabBackgroundColor label, or an empty string if it has none.

getScriptEnv
getScriptEnv(): "frontend" | "backend" | null

Returns where the note runs as a script: frontend for HTML, JSX, render notes and JavaScript with env=frontend in its MIME type, backend for JavaScript with env=backend, and null for any other note.

executeScript
executeScript(): Promise<unknown>

Runs the note as a frontend or backend script, depending on getScriptEnv(). For a frontend script, the promise resolves to the value the script returns; for a backend script, it resolves to undefined once the script has run. A frontend script that fails shows its error and resolves to undefined.

blobId

string
Blob ID of the current content; changes when content changes.

parentToBranch

Record<string, string>
Map of parent note ID → branch ID.

childToBranch

Record<string, string>
Map of child note ID → branch ID.

searchResultsLoaded
optional

boolean
For a search note, true once its results have been loaded as its children; otherwise not set.

highlightedTokens
optional

string[]
For a search note whose results are loaded, the search words to highlight in those results; otherwise not set.

dto

Record<string, unknown>
Plain data representation of the note (the live object minus its cache handle).

addParent
addParent(parentNoteId: string, branchId: string, sort?: boolean): void

Adds a parent to this note in the client's cache only. Trilium calls it when it loads branches; scripts do not normally call it, and the change is not saved. To place a note under another, use api.runOnBackend() with the backend API.

ParameterDescription
parentNoteIdstring
branchIdstring
the ID of the branch that links the two notes.
sort
optional
boolean
whether to reorder the parents afterwards. Defaults to true.
addChild
addChild(childNoteId: string, branchId: string, sort?: boolean): void

Adds a child to this note in the client's cache only. Trilium calls it when it loads branches; scripts do not normally call it, and the change is not saved.

ParameterDescription
childNoteIdstring
branchIdstring
the ID of the branch that links the two notes.
sort
optional
boolean
whether to reorder the children by their position afterwards. Defaults to true.
sortParents
sortParents(): void

Reorders the parent list in the client's cache so that ordinary parents come before search notes, archived notes and notes outside the visible tree. Trilium calls it itself; scripts do not normally call it.

sortChildren
sortChildren(): void

Reorders the child list in the client's cache by each branch's position. Trilium calls it itself; scripts do not normally call it, and it does not change the order saved in the database.

update
update(row: Record<string, unknown>): void

Overwrites the note's ID, title, type, MIME type, protection flag and blob ID in the client's cache with the values in row. Trilium calls it when changes arrive from the server; scripts do not normally call it, and the change is not saved.

invalidateAttributeCache
invalidateAttributeCache(): void

Does nothing; the note's attributes stay up to date without it.

toString
toString(): string

Returns a short description of the note for logging, such as Note(noteId=abc123, title=My note).

RightPanelWidget

Instance shape of RightPanelWidget (subset) — a widget shown in the right sidebar.

MemberDescription
$widget

JQuery
The widget's root element, which doRender() assigns, such as this.$widget = $(TPL).

isEnabled
isEnabled(): boolean | null | undefined

Returns whether the widget is shown: always for a BasicWidget, and only while a note is active for a NoteContextAwareWidget. A disabled widget stays in the DOM, hidden, and a NoteContextAwareWidget does not call refreshWithNote() while it is disabled.

doRender
doRender(): void

Builds the widget's DOM. Override it to create the root element and assign it to this.$widget as a jQuery object.

render
render(): JQuery

Renders the widget and returns its root element.

cleanup
cleanup(): void

Tears down the widget; override to release resources.

toggleInt
toggleInt(show: boolean | null | undefined): void

Shows or hides the widget from inside the widget itself, such as from refreshWithNote() when the note does not apply.

id
id(id: string): this

Fluent builder: set the element id. Chainable.

class
class(className: string): this

Fluent builder: add a CSS class. Chainable.

css
css(name: string, value: string): this

Sets an inline CSS property on the widget's root element, such as css("padding-inline-start", "12px"), and returns the widget for chaining. It takes effect when the widget renders.

child
child(...components: unknown[]): this

Fluent builder: append child components. Chainable.

note

FNote | null
The note currently shown in this widget's context.

noteId

string | undefined
The ID of note, such as for loadResults.isNoteContentReloaded(this.noteId).

notePath

string | null | undefined
The path of note in the tree, such as root/abc123/def456.

ntxId

string | null | undefined
The ID of the note context (split) this widget is attached to.

noteContext
optional

NoteContext
The note context (split) this widget is attached to.

isNote
isNote(noteId: string): boolean

Returns whether noteId is the note shown in this widget's context.

refreshWithNote
refreshWithNote(note: FNote | null | undefined): void | Promise<void>

Updates the widget for the note in its context. Override it to refresh the widget's content; it runs when that note changes and on refresh(), as long as isEnabled() returns true.

refresh
refresh(): void | Promise<void>

Forces a refresh against the current note.

widgetTitle

string
The title shown in the panel's header, Untitled widget unless overridden. The panel reads it once, when it renders.

doRenderBody
doRenderBody(): void | Promise<void>

Builds the panel's body. Override it to fill this.$body, the jQuery element the panel creates for the content, instead of doRender(). It can return a promise when the body needs asynchronous work; an error that promise rejects with is logged.

NoteContextAwareWidget

Instance shape of NoteContextAwareWidget (subset) — reacts to the active note.

MemberDescription
$widget

JQuery
The widget's root element, which doRender() assigns, such as this.$widget = $(TPL).

isEnabled
isEnabled(): boolean | null | undefined

Returns whether the widget is shown: always for a BasicWidget, and only while a note is active for a NoteContextAwareWidget. A disabled widget stays in the DOM, hidden, and a NoteContextAwareWidget does not call refreshWithNote() while it is disabled.

doRender
doRender(): void

Builds the widget's DOM. Override it to create the root element and assign it to this.$widget as a jQuery object.

render
render(): JQuery

Renders the widget and returns its root element.

cleanup
cleanup(): void

Tears down the widget; override to release resources.

toggleInt
toggleInt(show: boolean | null | undefined): void

Shows or hides the widget from inside the widget itself, such as from refreshWithNote() when the note does not apply.

id
id(id: string): this

Fluent builder: set the element id. Chainable.

class
class(className: string): this

Fluent builder: add a CSS class. Chainable.

css
css(name: string, value: string): this

Sets an inline CSS property on the widget's root element, such as css("padding-inline-start", "12px"), and returns the widget for chaining. It takes effect when the widget renders.

child
child(...components: unknown[]): this

Fluent builder: append child components. Chainable.

note

FNote | null
The note currently shown in this widget's context.

noteId

string | undefined
The ID of note, such as for loadResults.isNoteContentReloaded(this.noteId).

notePath

string | null | undefined
The path of note in the tree, such as root/abc123/def456.

ntxId

string | null | undefined
The ID of the note context (split) this widget is attached to.

noteContext
optional

NoteContext
The note context (split) this widget is attached to.

isNote
isNote(noteId: string): boolean

Returns whether noteId is the note shown in this widget's context.

refreshWithNote
refreshWithNote(note: FNote | null | undefined): void | Promise<void>

Updates the widget for the note in its context. Override it to refresh the widget's content; it runs when that note changes and on refresh(), as long as isEnabled() returns true.

refresh
refresh(): void | Promise<void>

Forces a refresh against the current note.

BasicWidget

Instance shape of BasicWidget (subset) — the base for custom frontend widgets.

MemberDescription
$widget

JQuery
The widget's root element, which doRender() assigns, such as this.$widget = $(TPL).

isEnabled
isEnabled(): boolean | null | undefined

Returns whether the widget is shown: always for a BasicWidget, and only while a note is active for a NoteContextAwareWidget. A disabled widget stays in the DOM, hidden, and a NoteContextAwareWidget does not call refreshWithNote() while it is disabled.

doRender
doRender(): void

Builds the widget's DOM. Override it to create the root element and assign it to this.$widget as a jQuery object.

render
render(): JQuery

Renders the widget and returns its root element.

cleanup
cleanup(): void

Tears down the widget; override to release resources.

toggleInt
toggleInt(show: boolean | null | undefined): void

Shows or hides the widget from inside the widget itself, such as from refreshWithNote() when the note does not apply.

id
id(id: string): this

Fluent builder: set the element id. Chainable.

class
class(className: string): this

Fluent builder: add a CSS class. Chainable.

css
css(name: string, value: string): this

Sets an inline CSS property on the widget's root element, such as css("padding-inline-start", "12px"), and returns the widget for chaining. It takes effect when the widget renders.

child
child(...components: unknown[]): this

Fluent builder: append child components. Chainable.

FBranch

A branch (parent↔child link) as seen by frontend scripts (subset of FBranch).

MemberDescription
branchId

string
The unique ID of the branch.

noteId

string
The ID of the child note that this branch places in the tree.

parentNoteId

string
The ID of the parent note.

notePosition

number
The place of the note among its siblings; the note tree lists siblings by ascending notePosition. Trilium spaces positions 10 apart.

prefix
optional

string
The prefix shown before the note's title in the note tree, for this placement of the note only. It is empty or missing when the branch has none.

isExpanded
optional

boolean
Whether the note tree shows this branch expanded, with the note's children visible.

getNote
getNote(): Promise<FNote | null>

Returns the child note, loading it from the server if the frontend cache does not hold it yet. Resolves to null if the note does not exist.

getNoteFromCache
getNoteFromCache(): FNote | undefined

Returns the child note from the frontend cache, without contacting the server. Returns undefined if the note is not loaded yet.

getParentNote
getParentNote(): Promise<FNote | null>

Returns the parent note, loading it from the server if the frontend cache does not hold it yet. Resolves to null if the note does not exist.

isTopLevel
isTopLevel(): boolean

Returns whether the branch places its note directly under the root note.

NoteContext

A split/tab context as seen by frontend scripts (subset of NoteContext).

MemberDescription
ntxId

string | null
The ID of the note context, which identifies one tab or split.

note

FNote | null
The note this context shows, or null if the context is empty.

notePath

string | null
The path of the note this context shows, as note IDs from root joined by /, such as root/abc123/def456. It is null when the context is empty.

getCodeEditor
getCodeEditor(): Promise<CodeEditor | null>

Returns the CodeMirror editor of the code note this context shows. Resolves to null if the context shows no code editor within 200 ms.

getTextEditor
getTextEditor(): Promise<TextEditor | null>

Returns the CKEditor instance of the editable text note this context shows. Resolves to null if the context shows no editable text note within 200 ms.

DayjsInstance

A date as day.js wraps it (subset).

MemberDescription
format
format(template?: string): string

Formats the date, such as "YYYY-MM-DD" for 2026-10-22. Without a template, it returns the ISO 8601 form with the UTC offset, such as 2026-10-22T14:03:05+02:00.

add
add(value: number, unit: string): DayjsInstance

Returns a new date, value units later. The date it is called on stays unchanged.

ParameterDescription
valuenumber
unitstring
The unit, such as "day", "week", "month" or "year".
subtract
subtract(value: number, unit: string): DayjsInstance

Returns a new date, value units earlier. The date it is called on stays unchanged.

ParameterDescription
valuenumber
unitstring
The unit, such as "day", "week", "month" or "year".
toDate
toDate(): Date

Returns the date as a JavaScript Date.

Types

JQuery

A jQuery object: one or more page elements with jQuery's methods, as $(…) returns. The jQuery API documentation describes them, and the script editor offers them as completions.

Dayjs

Minimal day.js surface (the real API exposes the full day.js factory).

type Dayjs = (date?: string | number | Date) => DayjsInstance

WidgetClass

Constructor type allowing class X extends api.Widget { … }.

type WidgetClass<T> = new (...args: unknown[]) => T

Func

type Func = ((...args: unknown[]) => unknown) | string

CreateNoteOpts

Options accepted by FrontendApi.createNote.

PropertyDescription
title
optional
string | null
Title of the new note.
content
optional
string | null
Content of the new note (HTML for text notes, source for code notes, etc.).
type
optional
string
Note type, e.g. "text" (default), "code", "book".
mime
optional
string
MIME type, e.g. "application/javascript;env=frontend" for a frontend code note.
templateNoteId
optional
string
Note ID of a template to apply to the new note.
isProtected
optional
boolean
Create the note as protected (only takes effect when a protected session is available).
activate
optional
boolean
Activate (open) the new note after creation. Defaults to true.
focus
optional
"title" | "content"
Which part of the activated note to focus. Defaults to "title".
target
optional
string
Where to place the note relative to the parent/target: "into" (default) or "after".
targetBranchId
optional
string
Branch ID used together with target: "after".
attributes
optional
CreateAttribute[]
Attributes to set atomically on creation.

TextEditor

The editor of a text note, a CKEditor 5 editor. The CKEditor 5 API documentation describes it; editor.model and editor.getData() are the usual starting points.

CodeEditor

The editor of a code note, a CodeMirror 6 EditorView. The CodeMirror reference describes it; editor.state.doc.toString() reads the code.

PickerItem

One thing a picker offers, as pickSingleItem takes and answers with.

PropertyDescription
keystring
The ID of the item. It must be unique within its group, and tells the script which item the user picked.
captionstring
The text shown for the item. The search field filters items by it.
icon
optional
string
An icon class, bx prefix included.
tooltip
optional
string
HTML shown in a tooltip while the item is hovered.

PickerItemGroup

A run of picker items under a heading of their own.

PropertyDescription
keystring
The ID of the group. It must be unique among the groups.
groupHeaderstring
The heading shown above the group's items. An empty string shows the items without a heading.
itemsPickerItem[]
The items in the group, in the order the picker shows them.

LinkOptions

Options of api.createLink().

PropertyDescription
title
optional
string
The text of the link. Defaults to the note's title.
showTooltip
optional
boolean
Whether a preview of the note shows while the mouse pointer rests on the link. Defaults to true.
showNotePath
optional
boolean
Whether the path of the note's parents shows below the link. Defaults to false.
showNoteIcon
optional
boolean
Whether the note's icon shows before the link. Defaults to false.
referenceLink
optional
boolean
Whether the link is styled as a reference link, as in text notes. Defaults to false.
autoConvertToImage
optional
boolean
Whether an image, canvas or Mermaid note shows as its picture instead of a link. Defaults to false.
titleSuffix
optional
string
Text shown right after the link's title.

Preact

The Preact API that render notes import from trilium:preact: Preact's own functions and hooks, and Trilium's components and defineWidget(). In a JSX note, the script editor offers its full type.

NotePathRecord

One resolved tree path to a note (subset of the client's NotePathRecord).

PropertyDescription
isArchivedboolean
Whether a note on the path, the note itself included, is archived, which means it has the #archived label, owned or inherited.
isInHoistedSubTreeboolean
Whether the path passes through the hoisted note passed to getSortedNotePathRecords(). It is always true when the hoisted note is root.
isSearch
optional
boolean
Whether the note itself is a search note. Only frontend scripts get this property; backend records leave it out.
notePathstring[]
The note IDs along the path, from root to the note itself.
isHiddenboolean
Whether the path passes through the hidden subtree, _hidden, which holds Trilium's system notes.

Attribute

A label or relation attached to a note.

PropertyDescription
attributeIdstring
The ID of the attribute.
type"label" | "relation"
The type of the attribute: label or relation.
namestring
The name of the attribute, without the # or ~ prefix.
valuestring
The value of the attribute. For a relation, it is the ID of the target note. For a label without a value, it is an empty string.
isInheritableboolean
Whether the note's descendants inherit the attribute.
isOwnedboolean
Not set by Trilium: neither frontend nor backend attributes carry this property, so it reads undefined.

Blob

A note's binary/text content blob (subset of the client's FBlob).

PropertyDescription
blobIdstring
The ID of the blob, derived from its content. Notes, attachments and revisions with identical content share one blob.
contentstring
The content as text. It is null when the content is binary, as in images and files.
contentLengthnumber
The length of the content as stored: characters for text, bytes for binary content. For a protected note, it measures the encrypted content.
dateModifiedstring
The local date and time this content was first stored, with the UTC offset, such as 2026-10-22 14:03:05.123+0200. A blob never changes, so new content gets a new blob.
utcDateModifiedstring
The date and time, in UTC, that this content was first stored, such as 2026-10-22 12:03:05.123Z.

NoteMetadata

Creation/modification timestamps returned by FNote.getMetadata.

PropertyDescription
dateCreatedstring
The local date and time the note was created, with the UTC offset, such as 2026-10-22 14:03:05.123+0200.
utcDateCreatedstring
The date and time, in UTC, that the note was created, such as 2026-10-22 12:03:05.123Z.
dateModifiedstring
The local date and time the note was last modified, with the UTC offset, such as 2026-10-22 14:03:05.123+0200. A change to the note's content counts as a modification.
utcDateModifiedstring
The date and time, in UTC, that the note was last modified, such as 2026-10-22 12:03:05.123Z. A change to the note's content counts as a modification.

Attachment

An attachment as seen by frontend scripts (subset of the client's FAttachment).

PropertyDescription
attachmentIdstring
The ID of the attachment.
ownerIdstring
The ID of the note the attachment belongs to. For an attachment of a revision, it is the ID of the revision.
rolestring
The purpose of the attachment, such as image for an image shown in a text note or file for an attached file. Trilium also uses roles of its own, such as viewConfig for a collection's view settings.
mimestring
The MIME type of the attachment's content, such as image/png.
titlestring
The title of the attachment, usually its file name.
utcDateModifiedstring
The date and time, in UTC, that the attachment was last saved, such as 2026-10-22 12:03:05.123Z. Replacing the content counts as saving.
contentLengthnumber
The length of the attachment's content. Only some ways of loading an attachment fill it in, such as getAttachments().

CreateAttribute

An attribute to create together with a note (see CreateNoteOpts.attributes).

PropertyDescription
type"label" | "relation"
The type of the attribute: label or relation.
namestring
The name of the attribute, without the # or ~ prefix.
value
optional
string
The value of the attribute. For a relation, it is the ID of the target note. Defaults to an empty string.
isInheritable
optional
boolean
Whether the note's descendants inherit the attribute. Defaults to false.
position
optional
number
The place of the attribute among the note's attributes, which are listed by ascending position. Defaults to 10 more than the highest position among the note's attributes.