Skip to content
undertext developers
Skip to Content
undertext developers

Embed API

Every option, event and method of the editor and seals you embed with @undertext/embed, and what your page needs to allow it.

The embed puts the Undertext editor in your page as an iframe served from embed.undertext.sh. Your page passes it a document id and a way to get session tokens; everything the person does inside it goes straight to Undertext. For a walkthrough, see Embed the editor.

Install

From npm, for pages you bundle:

npm install @undertext/embed
import { mountEditor, mountPresenceSettings, mountSeal, openPresenceSettings } from "@undertext/embed";

Or with a script tag, which defines window.Undertext with the same four functions:

<script src="https://embed.undertext.sh/v1.js"></script>
<script>
  const editor = Undertext.mountEditor(document.getElementById("editor"), { document: "doc_8Hq2Lm4R", getToken });
</script>

The package is a few kilobytes: it creates the iframe and passes messages to it. The editor itself always loads from embed.undertext.sh, so it stays current without a new release of your page. v1.js only changes in ways that keep your code working.

mountEditor

const editor = mountEditor(element, options);

element is the container the iframe goes in; it replaces anything inside it. mountEditor returns the editor at once and loads it in the background: wait for the ready event before calling methods that need the document.

page.ts
const editor = mountEditor(document.querySelector("#editor")!, {
  document: "doc_8Hq2Lm4R",
  getToken: async (doc) => {
    const response = await fetch(`/undertext/session?doc=${doc}`, { method: "POST" });
    return (await response.json()).token;
  },
  comments: "right",
  colorScheme: "auto",
});

Options

OptionTypeDefaultWhat it does
documentstringrequiredThe document to open.
getToken(document: string) => Promise<string>requiredReturns a fresh session token for document and the person viewing it: the one open, or one open opens. The embed asks for no other, whatever the frame says.
mode"edit" or "suggest""edit" where the role allowsWhether the person's changes are made or proposed. A suggester always suggests and a viewer only reads, whatever you pass.
colorScheme"light", "dark" or "auto""light""auto" follows the person's system setting.
toolbar"header", "floating" or "none""header"Where the format bar goes: along the top, floating at the bottom, or nowhere (Markdown shortcuts and the ⌘K palette still work). Along the top it keeps to one row, with the buttons there isn't room for under » at its end.
chrome"full" or "compact""full"Use "compact" when your host provides navigation, save status, authorship, and sealing actions. It removes duplicate status and the floating seal, keeps collaborators and role notices, and offers touch-sized formatting buttons with the other tools under More. Use it with toolbar: "floating".
comments"right", "left" or "hidden""right"Where comment and suggestion cards go. Where the frame is too narrow, they go in a panel. "hidden" hides comments but not suggestions.
highlightbooleanfalseTint text by who wrote it, and show the attribution rail beside each line.
height"auto" or "fill""auto"See Sizing.
target{ kind, id }noneA comment (kind: "comment", a thread id) or suggestion to open once the document has loaded, as from a notification or a link.
autofocusbooleantruePut the caret in the text once it loads. Pass false when your page shows something first, and call focus() when it's ready.
originstringwhere v1.js came from, or https://embed.undertext.sh (also for your own bundle of the package)Where Undertext serves the editor.

These shape the editor around your own page's controls:

OptionTypeWhat it does
headerItems{ id, icon, label, badge?, side?, popup?, expanded? }[]Buttons of your own in the editor's header, such as a menu or a notification bell: at its end, after who's here (side: "end", the default), or at its start, before the format bar ("start"). icon is "bell", "more" or "sidebar"; label names it to screen readers and is its tooltip; badge is a short count shown on it, such as "3" or "9+". A click sends a command event with its id and where the button is, for your page to open its menu or panel there. For a button that opens something, set popup ("menu" or "dialog"), and keep expanded current as what it opens opens and closes.
pageLeftnumberHow far, in pixels, the frame's left edge is from your page's, as beside a sidebar. The editor's dialogs then centre on your page rather than the frame, as far as the frame allows. Update it with setOptions when the sidebar resizes.
commentPane{ axis: "horizontal" or "vertical", start: number, end: number } or nullGive comments their own pane after a gutter, measured in the frame's CSS pixels. Writing sits before start, discussion after end. Use the gutter for a fold or other reserved area. Each pane needs at least 280px horizontally or 160px vertically; otherwise the normal margin is used. null restores the normal margin.
commands{ title, items }[]Groups of your own items for the editor's ⌘K palette. Each item is { id, label, hint?, checked?, disabled? }; choosing one sends a command event with its id.
shortcutsstring[]Keys your page listens for, such as "mod+k", that the editor passes on as a shortcut event while it has focus.
trashActionsbooleanFor a document in the person's trash, the card at the foot offers Restore and Delete forever, sending command events restore and delete.

Change any of these after mounting with editor.setOptions({ ... }). What you set is kept if the frame reloads, as it does when the person's access changes.

Tokens

The editor calls getToken when it mounts, and again two minutes before each token lapses (tokens last 15 minutes), so a page left open keeps working; an open connection carries on with the new token. If a call fails, the editor keeps the person's changes and the embed tries again after 1, 2, 5, 10 and 30 seconds; while the browser is offline, it waits until it's back online instead. If it still fails, as when your server refuses because the person lost access, the editor emits an error event with code token_rejected and stops asking.

Your server makes the token with POST /v1/sessions. Check that the signed-in person may open the document before you do: the token is how Undertext knows who is writing.

Events

const stop = editor.on("title", ({ title }) => (document.title = `${title} · Acme Notes`));
stop(); // stops listening

on returns a function that removes the handler.

EventPayloadWhen
ready{ document, role, mode, user }The document has loaded. role is "owner", "editor", "suggester" or "viewer"; user is the person's Undertext id.
title{ title, name }The document's title changed: name is the name an editor gave it, or null; title is that, or its first line. Also sent once after ready.
save-state{ state, unsaved }"saving" while changes are on their way, "saved" once Undertext has them, "offline" while the connection is down. unsaved is true while some change hasn't reached Undertext, for warning before the page closes. Changes made offline are kept and sent on reconnecting.
focus{ focused }Whether the writing surface has keyboard focus. A surrounding app can use this to make more room for writing.
status{ mode, comments, openComments, sealed, role, trashed, verifiedPresence }What your own controls show of the editor, whenever it changes: its mode, whether comments are shown and how many are open, whether it has a seal, the person's role, whether it's in their trash, and Verified Presence for them, { on, required }: whether it's on, and whether your platform requires it, so it can't be turned off. null for someone who can't write in the document, who has no Verified Presence there.
seal{ code, url, line }The person sealed the document with the editor's Seal button. The seal.created webhook follows.
open-document{ document, href }The person followed a link to another document of yours. Navigate to it in your own way; the editor doesn't.
thread-read{ thread }The person read a thread, by opening it or writing in it: clear your notifications of it.
target{ target }A comment's or suggestion's card opened ({ kind, id }), or closed (null). Name it in your page's address with targetHash, so the address links to it.
command{ id, anchor?, expanded? }The person chose one of your commands or headerItems, or a trash action. From a header button, anchor is where the button is in your page's window, as { left, top, right, bottom }, and expanded is whether what it opens was open as it was pressed. Close what a header button opens when your page loses focus, as it does to any click in the frame; a press with expanded: true was one of those, so don't open it again. When what it opened closes and you give focus back to the frame, the editor puts it on the button.
shortcut{ key }The person pressed one of your shortcuts in the editor.
presence-settings{}The person needs presence settings, to add a key: from a check-in, or turning Verified Presence on without a key. Open them, framed or in their window.
overlay{ open }A dialog opened in the frame, or closed: dim your page around it, which its backdrop can't reach, and close it with closeDialog() on a click there.
settingsoptionsThe person changed a display setting from inside the editor, such as the theme or where comments go: keep it, and pass it back next time.
height{ height }The document's height changed. With height: "auto", the embed resizes the frame itself.
error{ code, message }Something stopped the editor. See below.

Error codes

CodeWhat happened
token_rejectedgetToken failed for good, or returned a token Undertext doesn't accept.
no_accessThe token's person can no longer open the document.
document_deletedThe document was deleted while it was open.

Handle the event to show your own message, or to send the person elsewhere. On a page whose origin isn't one of your embed origins, the browser refuses to show the frame at all, and no event comes.

Methods

MethodWhat it does
editor.focus()Puts the caret back where it was in the document.
editor.setMode(mode)Switches between "edit" and "suggest", within what the role allows.
editor.print(options?)Prints the document, typeset, without the editor around it. { sealLine: true } ends it with the document's seal line, as export does.
editor.export(format, options?)Resolves to the document as "markdown" or "html" text, or as a Blob for "docx". Pending suggestions are left out. The HTML is sanitized: nothing in it runs. With { sealLine: true }, it ends with the seal line of the document's newest seal, its address linking to the seal's page. That needs the newest seal to read as the document does now: otherwise it rejects with an error whose code is seal_changed, or not_sealed when the document has no seal, so that a seal never vouches for words it doesn't say.
editor.openBreakdown()Opens the breakdown behind the live seal: where the words came from, presence, prompts and sittings.
editor.openSeal()Opens the seal dialog. Anyone who can open the document sees its seals, their links and who reads them; its editors also see the readers listed; its owners also seal, choose who reads its seals, answer people asking to read them, and withdraw versions.
editor.openPalette()Opens the ⌘K palette.
editor.showTarget({ kind, id })Scrolls to a comment or suggestion and opens its card.
editor.comment()Starts a comment on the selection.
editor.toggleComments()Shows comments beside the text or hides them; in the narrow panel, opens or closes it.
editor.setVerifiedPresence(on)Turns Verified Presence on or off for the person in this document, for those who can write in it: on, they're asked to check in as they write here. Resolves to whether it's on. Without a key it stays off and the editor sends presence-settings; it turns on once they come back to the editor with a key. Where your platform requires it, it stays on. See Set up check-ins.
editor.closeDialog()Closes the dialog the editor has open, as for a click on your page where you dim it during overlay.
editor.open(document, { target })Opens another document in place of the one open. See Opening another document.
editor.setOptions(options)Changes options after mounting.
editor.destroy()Removes the iframe and its listeners. Changes already made are kept.

Methods return promises, which resolve once the editor has done it.

Opening another document

Where people move between documents, as from a list beside the editor, open each in the same editor rather than mounting another: the editor isn't loaded again, and the next document loads while the one before stays in view.

await editor.open("doc_3Fw9Kp2T", { target: null });

It asks getToken for the next document's token. The one open stays in view, unusable, until the next has loaded, or for a second at most; it then shows how far it has got. The promise resolves once the next is in view, and rejects if it can't be opened, which leaves the one before, or if another is opened first. From the call on, events are the next document's: ready once it has loaded.

editor.role and editor.mode hold the current role and mode once ready has fired.

A link to a document can open a comment's or suggestion's card: the links Undertext's agents give to a comment or suggestion, and the editor's own Copy link on a card, are your document_url followed by #comment-<id> or #suggestion-<id>. Without a document_url, cards offer no link. Read the target from your page's address and pass it on, and keep the address naming the open card as cards open and close:

import { mountEditor, parseTarget, targetHash } from "@undertext/embed";

const editor = mountEditor(element, { document, getToken, target: parseTarget(location.hash) });
editor.on("target", ({ target }) => history.replaceState(null, "", location.pathname + location.search + (target ? targetHash(target) : "")));
NameWhat it does
parseTarget(hash)The { kind, id } a link's hash names, or null.
targetHash(target)The hash that opens target's card, for links you make yourself.

Both are also at @undertext/embed/links, which needs no browser, for links your server builds, and on window.Undertext from v1.js.

Presence settings

Security keys must be added on Undertext's own domain, so people add them in Undertext's presence settings: framed in your own settings page, or in a small window of their own. Both take a token from POST /v1/sessions with purpose: "presence".

mountPresenceSettings

const presence = mountPresenceSettings(element, {
  getToken: () => fetch("/undertext/presence-session", { method: "POST" }).then((r) => r.json()).then((r) => r.token),
  platform: "acme",
  colorScheme: "auto",
}, (choice) => console.log(choice)); // { keys: 1 }

platform is your platform's slug: framed, presence settings load only on your embed origins. colorScheme is as the editor's; framed, the settings have no background of their own, so your page shows through. The callback hears each change. presence.setOptions({ colorScheme: "dark" }) changes the colour scheme, and presence.destroy() removes the frame. Browsers that won't create a security key in a frame need the window instead.

openPresenceSettings

button.addEventListener("click", async () => {
  const result = await openPresenceSettings({
    getToken: () => fetch("/undertext/presence-session", { method: "POST" }).then((r) => r.json()).then((r) => r.token),
  });
  console.log(result); // { keys: 1 }
});

It takes a colorScheme too. Call it from a click or key press, or the browser blocks the window. The promise resolves when the person closes the window, with how many keys they have. See Set up check-ins.

Seals

mountSeal

A seal on your own seal page, at your seal_url: the sealed text, the seal and its breakdown, drawn by Undertext in an iframe from embed.undertext.sh, so what it shows is Undertext's whatever your page does. It fills its element: give the element a height, such as the whole window. See Show seals on your site.

const seal = mountSeal(element, {
  code: "66G4LF343",
  getToken: () => fetch("/undertext/seal-session", { method: "POST" }).then((r) => (r.ok ? r.json().then((r) => r.token) : null)),
  onSignIn: () => location.assign(`/sign-in?next=${encodeURIComponent(location.pathname)}`),
  colorScheme: "auto",
});
seal.on("ready", ({ state, title }) => (document.title = title ?? "Undertext"));
OptionTypeDescription
codestring, requiredThe seal's code, from your page's address.
getToken(code) => Promise<string | null>A token from POST /v1/sessions with purpose: "seal", for the person signed in with you, or null when nobody is. Called only when the seal is private, once; if it throws, the seal is shown as to someone with no session.
onSignIn(reader) => voidWhen given, a private seal's page offers to sign in, and calls this. reader is { email } when your session's person isn't among its readers, so you can offer another account; null when you gave no session.
originstringWhere Undertext serves its frames. Defaults to https://embed.undertext.sh.
colorScheme"light", "dark" or "auto"As the editor's.
EventPayloadWhen
ready{ state, title }It has shown the seal (state: "sealed", with its title), that it was withdrawn ("withdrawn"), or that it's private to this reader ("private").
sign-in{ reader }The reader asked to sign in, as onSignIn hears.

Someone signed in whose email your session vouched for, and whom a private seal doesn't let in, can ask its owners to let them read it, with a message, in the frame; it says so when they come back. See Private seals.

seal.setOptions({ colorScheme }) changes the colour scheme, and seal.destroy() removes the frame. Links to the seal's other versions open your seal page for them, in place of the page around the frame. A private seal's password is typed in the frame and goes to Undertext alone; what it earns is kept in the frame, for 30 days.

Embed origins

The editor loads only on the origins you list under Embed origins in the console. Undertext serves it with a Content-Security-Policy: frame-ancestors header naming exactly those origins, and the editor framed there opens only your platform's documents, taking messages only from the page that frames it, so another site can't frame your users' documents, even with a token of yours. List each origin in full, for example https://acme.com and https://www.acme.com. Plain http is allowed only for localhost and 127.0.0.1, such as http://localhost:5173, for development. Set them with PATCH /v1/platform too.

If your own page sends a Content Security Policy, it needs:

DirectiveValueFor
frame-srchttps://embed.undertext.shThe editor, seals and the presence window.
script-srchttps://embed.undertext.shOnly with the v1.js script tag.

The iframe asks for two permissions: publickey-credentials-get, for check-ins with a security key, and clipboard-write, for copying a seal line; framed presence settings ask for publickey-credentials-create too, to add a key. If your page sends a Permissions-Policy header, it must not deny them to https://embed.undertext.sh, or check-ins can't run.

Sizing

With height: "auto", the iframe grows and shrinks with the document, and your page scrolls as it would with any long content. Use it when the document sits in the flow of a page.

With height: "fill", the iframe fills its container and the document scrolls inside it. Give the container a height, for example with flex or grid. Use it for a full-window editor beside your own sidebar.

The editor is at least 320 pixels tall either way, and needs 720 pixels of width to put comments beside the text.

Keyboard and focus

While the editor has focus, keys go to it: ⌘K (Ctrl+K) opens its palette for this document, ⌘P prints the document, and Tab indents list items. Press Esc, then Tab, to move focus out of the editor to the next control on your page. Shortcuts your page listens for on window don't fire while the editor has focus, unless you list them in shortcuts.

Appearance

You choose the colour scheme, full or compact controls, where the toolbar and comments go, whether authorship is highlighted, and buttons of your own in the header. Compact controls reduce space around the document for native hosts; the document itself is fixed, so every Undertext editor reads the same way to the people who verify what was written in it:

  • The document's typefaces and paragraph spacing.
  • The seal's colours, which stand for where words came from.
  • The blocks people can write: headings, lists, checklists, quotes, code, links, images and tables. You can't add your own.

There is no custom CSS. If your page needs something the options don't give, tell us.

Storage and cookies

The editor and seals set no cookies and need none: everything rides on the session token. Browsers keep a framed site's storage apart from the same site opened directly, so the editor doesn't rely on it; a seal keeps what its password earned there, per site that frames it, and asks for the password again where it can't. Display settings a person changes in the editor come to your page as a settings event, for you to keep with your other preferences and pass back as options.

Browsers

The editor supports the two latest versions of Chrome, Edge, Firefox and Safari, on desktop and on iOS and Android. Check-ins with a security key need a browser that allows WebAuthn in a frame, which those versions do. Older browsers aren't supported.

On this page