Skip to content

Build your personal knowledge base with Trilium Notes

feat(clipper): save the page's description with every clip of the page (#802)

Elian Doran1b047edd0e79
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Installation & Setup/Web Clipper.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Installation & Setup/Web Clipper.html
index 363b1b5f19..092d518fd7 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Installation & Setup/Web Clipper.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Installation & Setup/Web Clipper.html
@@ -32,8 +32,9 @@
<ul>
<li>
<p>The popup shows what will be saved from the current page: the note's title,
- which can be edited before saving, the website, and below them a preview.
- A switch above the preview chooses what to save, among what the page offers:</p>
+ which can be edited before saving, the website, the page's description
+ if it has one, and below them a preview. A switch above the preview chooses
+ what to save, among what the page offers:</p>
<ul>
<li><em>Selection</em>, when text is selected on the page: <em>Save selection</em> saves
it into the note of that page's clippings, as the context menu does.</li>
@@ -43,11 +44,14 @@
<li><em>Bookmark</em>, always: a text box for a note about the page replaces
the preview, and <em>Save bookmark</em> (or <kbd>Ctrl</kbd>+<kbd>Enter</kbd>)
saves a link to the page with that note. Left empty, the title stays the
- page's title. If the page describes itself (in its <code>description</code> meta
- tag, or the one it gives social sites), the description is shown above
- the text box, where it can be edited or cleared, and is saved in the note's <code>#pageDescription</code> label.
- The label is updated when the page is bookmarked again.</li>
+ page's title.</li>
</ul>
+ <p>The description comes from the page's <code>description</code> meta tag,
+ or the one it gives social sites. It can be edited or cleared before saving,
+ and is saved in the <code>#pageDescription</code> label of the note. Clippings
+ saved with the keyboard shortcuts or the context menu, screenshots and
+ images included, get the description as the page gives it. Each clipping
+ that brings a description updates the label.</p>
<p>The popup opens on the selection if there is one, otherwise on the article.
On a page with no article (Readability cannot find one) and no selection,
it opens on <em>Bookmark</em> and says the page has no article. The keyboard
@@ -100,6 +104,9 @@
title and thumbnail. As with a link preview added in the editor, the video
plays only when clicked. Other embedded content (such as videos from other
websites) is not saved.</p>
+<p>The popup's preview shows each such video as a chip with the YouTube icon
+ and the video's short link, and leaves out the embedded content that will
+ not be saved.</p>
<h2>Keyboard shortcuts</h2>
<p>Keyboard shortcuts are available for most functions:</p>
<ul>
diff --git a/apps/server/src/routes/api/clipper.spec.ts b/apps/server/src/routes/api/clipper.spec.ts
index 375149d165..d0bc5ef6f4 100644
--- a/apps/server/src/routes/api/clipper.spec.ts
+++ b/apps/server/src/routes/api/clipper.spec.ts
@@ -132,6 +132,23 @@ describe("clipper route handlers", () => {
expect(found.noteId).toBe(first.noteId);
});
+ it("labels a clipping note, refreshed by each clipping that brings labels", async () => {
+ const pageUrl = "https://example.com/described";
+ const clip = (labels?: Record<string, string>) => cls.init(() => clipperRoute.addClipping({
+ body: { title: "Described", content: "<p>x</p>", images: [], pageUrl, labels }
+ } as unknown as Request));
+
+ const { noteId } = await clip({ pageDescription: "Tom & <b>Jerry</b>" });
+ const clipping = becca.getNoteOrThrow(noteId);
+ expect(clipping.getLabelValue("pageDescription")).toBe("Tom & Jerry");
+
+ await clip({ pageDescription: "Updated" });
+ expect(clipping.getLabelValue("pageDescription")).toBe("Updated");
+
+ await clip();
+ expect(clipping.getLabelValue("pageDescription")).toBe("Updated");
+ });
+
it("appends to a clipping note moved out of the inbox without cloning it back", async () => {
const pageUrl = "https://example.com/moved";
const first = await cls.init(() => clipperRoute.addClipping({
diff --git a/apps/server/src/routes/api/clipper.ts b/apps/server/src/routes/api/clipper.ts
index c21e4d2b3c..091d43b063 100644
--- a/apps/server/src/routes/api/clipper.ts
+++ b/apps/server/src/routes/api/clipper.ts
@@ -17,7 +17,7 @@ async function addClipping(req: Request) {
// if a #clipType=clippings note exists with the same 'pageUrl' attribute,
// append the content to that note
// otherwise create a new note under clipperInbox (or today's note)
- const { title, content, images } = req.body;
+ const { title, content, images, labels } = req.body;
const clipType = "clippings";
const pageUrl = sanitize.sanitizeUrl(req.body.pageUrl);
@@ -37,6 +37,8 @@ async function addClipping(req: Request) {
clippingNote.setLabel("iconClass", "bx bx-globe");
}
+ setLabels(clippingNote, labels);
+
const rewrittenContent = await processContent(images, clippingNote, content);
const existingContent = clippingNote.getContent();
@@ -113,11 +115,7 @@ async function createNote(req: Request) {
}
}
- if (labels) {
- for (const labelName in labels) {
- note.setLabel(labelName, sanitizeLabelValue(labels[labelName]));
- }
- }
+ setLabels(note, labels);
const existingContent = note.getContent();
if (typeof existingContent !== "string") {
@@ -134,6 +132,13 @@ async function createNote(req: Request) {
};
}
+/** Sets each label the extension sends, replacing the value a previous clipping set. */
+function setLabels(note: BNote, labels: Record<string, string> | undefined) {
+ for (const labelName in labels) {
+ note.setLabel(labelName, sanitizeLabelValue(labels[labelName]));
+ }
+}
+
/**
* Label values are plain text, so every tag is removed. `sanitize-html` writes `&` as `&amp;`;
* turning it back cannot produce markup, since no `<` comes out of it.
diff --git a/apps/web-clipper/entrypoints/background/index.spec.ts b/apps/web-clipper/entrypoints/background/index.spec.ts
index 93cd981212..2b9890e4e9 100644
--- a/apps/web-clipper/entrypoints/background/index.spec.ts
+++ b/apps/web-clipper/entrypoints/background/index.spec.ts
@@ -488,6 +488,37 @@ describe("background", () => {
expect(await lastToast()).toMatchObject(FAILURE_TOAST);
});
+ it("labels screenshots and images with the page's description", async () => {
+ tabMessageHandler = (message) => message.name === "trilium-get-page-metadata"
+ ? { description: "About the page" }
+ : undefined;
+ await sendRuntimeMessage({ name: "save-whole-screenshot" });
+ expect(lastPayload()).toMatchObject({ labels: { pageDescription: "About the page" } });
+ await onContextMenuClicked({
+ menuItemId: "trilium-save-image",
+ srcUrl: "https://example.com/cat.png",
+ pageUrl: PAGE_URL
+ });
+ expect(lastPayload()).toMatchObject({ labels: { pageDescription: "About the page" } });
+
+ tabMessageHandler = () => ({});
+ await sendRuntimeMessage({ name: "save-whole-screenshot" });
+ expect(lastPayload()).not.toHaveProperty("labels");
+
+ // An outdated content script answers nothing; none runs on browser pages.
+ tabMessageHandler = () => undefined;
+ await sendRuntimeMessage({ name: "save-whole-screenshot" });
+ expect(lastPayload()).not.toHaveProperty("labels");
+
+ tabMessageHandler = () => {
+ throw new Error("Could not establish connection.");
+ };
+ facade.callService.mockClear();
+ await sendRuntimeMessage({ name: "save-whole-screenshot" });
+ expect(lastPayload()).not.toHaveProperty("labels");
+ expect(facade.callService).toHaveBeenCalledOnce();
+ });
+
it("saves a link, with its URL as the text when the browser gives none", async () => {
await onContextMenuClicked({ menuItemId: "trilium-save-link", pageUrl: PAGE_URL });
expect(facade.callService).not.toHaveBeenCalled();
diff --git a/apps/web-clipper/entrypoints/background/index.ts b/apps/web-clipper/entrypoints/background/index.ts
index 8b2da8e5a8..5554990f7d 100644
--- a/apps/web-clipper/entrypoints/background/index.ts
+++ b/apps/web-clipper/entrypoints/background/index.ts
@@ -14,6 +14,8 @@ type BackgroundMessage = {
name: "trilium-get-rectangle-for-screenshot";
} | {
name: "trilium-save-page";
+} | {
+ name: "trilium-get-page-metadata";
};
/** An image of a clipping; `content` references it by `imageId` until Trilium stores it. */
@@ -270,11 +272,13 @@ export default defineBackground(() => {
async function getImagePayloadFromSrc(src: string, pageUrl: string | null | undefined) {
const imageId = randomString(20);
const activeTab = await getActiveTab();
+ const { description } = await readPageMetadata();
const payload = {
title: activeTab.title,
content: `<img src="${imageId}">`,
images: [ { imageId, src } ],
- pageUrl
+ pageUrl,
+ ...(description && { labels: { pageDescription: description } })
};
const failedImages = await postProcessImages(payload);
@@ -282,6 +286,19 @@ export default defineBackground(() => {
return { payload, failedImages };
}
+ /**
+ * What the page says about itself. A screenshot or an image is saved without it where no
+ * content script answers: on browser pages, and on a page loaded before the extension was
+ * updated.
+ */
+ async function readPageMetadata(): Promise<{ description?: string }> {
+ try {
+ return await sendMessageToActiveTab({ name: "trilium-get-page-metadata" }) ?? {};
+ } catch {
+ return {};
+ }
+ }
+
async function saveCroppedScreenshot(pageUrl: string | null | undefined) {
const { rect, devicePixelRatio } = await requestFromPage({
name: 'trilium-get-rectangle-for-screenshot'
diff --git a/apps/web-clipper/entrypoints/content/index.spec.ts b/apps/web-clipper/entrypoints/content/index.spec.ts
index be501aca13..5220a07757 100644
--- a/apps/web-clipper/entrypoints/content/index.spec.ts
+++ b/apps/web-clipper/entrypoints/content/index.spec.ts
@@ -11,7 +11,8 @@ type Clipping = {
title: string,
content: string,
images: { imageId: string, src: string }[],
- pageUrl: string
+ pageUrl: string,
+ labels: Record<string, string>
};
const PARAGRAPH = "Trilium is a hierarchical note taking application with focus on "
@@ -45,11 +46,14 @@ describe("content script", () => {
<img src="/cat.png">
<img>
<p id="end">After</p>`;
+ document.head.insertAdjacentHTML(
+ "beforeend", "<meta name=\"description\" content=\"About the post\">");
selectRange("start", "end");
const response = await send<Clipping>({ name: "trilium-save-selection" });
expect(response.title).toBe("Post title");
+ expect(response.labels).toEqual({ pageDescription: "About the post" });
expect(response.pageUrl).toBe("https://example.com/blog/post.html?id=1#comments");
expect(response.images.map((image) => image.src)).toEqual([
"https://example.com/cat.png",
@@ -91,7 +95,9 @@ describe("content script", () => {
document.body.innerHTML = "<p id=\"p\">Text</p>";
selectRange("p", "p");
expect(document.getElementsByTagName("title")).toHaveLength(0);
- expect(await send({ name: "trilium-save-selection" })).toMatchObject({ title: "" });
+ const untitled = await send<Clipping>({ name: "trilium-save-selection" });
+ expect(untitled.title).toBe("");
+ expect(untitled.labels).toEqual({});
document.title = " Fallback ";
expect(await send({ name: "trilium-save-selection" }))
@@ -108,7 +114,8 @@ describe("content script", () => {
document.head.innerHTML = `
<title>Article title</title>
<meta property="article:published_time" content="2026-01-02T10:00:00Z">
- <meta property="article:modified_time" content="2026-02-03T10:00:00Z">`;
+ <meta property="article:modified_time" content="2026-02-03T10:00:00Z">
+ <meta property="og:description" content="About the article">`;
document.body.innerHTML = `
<nav><a href="/">Home</a></nav>
<article>
@@ -126,7 +133,11 @@ describe("content script", () => {
title: "Article title",
pageUrl: "https://example.com/blog/post.html?id=1",
clipType: "page",
- labels: { publishedDate: "2026-01-02", modifiedDate: "2026-02-03" },
+ labels: {
+ pageDescription: "About the article",
+ publishedDate: "2026-01-02",
+ modifiedDate: "2026-02-03"
+ },
images: [ {
imageId: expect.any(String),
src: "https://example.com/blog/figure.png"
@@ -140,7 +151,7 @@ describe("content script", () => {
it("adds no labels without dates and fails when Readability finds no article", async () => {
document.body.innerHTML = `<article><p>${PARAGRAPH.repeat(5)}</p></article>`;
- expect(await send({ name: "trilium-save-page" })).toMatchObject({ labels: {} });
+ expect((await send<Clipping>({ name: "trilium-save-page" })).labels).toEqual({});
document.body.innerHTML = "";
vi.spyOn(Document.prototype, "cloneNode")
diff --git a/apps/web-clipper/entrypoints/content/index.ts b/apps/web-clipper/entrypoints/content/index.ts
index 114d18ff9f..fe63561239 100644
--- a/apps/web-clipper/entrypoints/content/index.ts
+++ b/apps/web-clipper/entrypoints/content/index.ts
@@ -65,6 +65,12 @@ export default defineContentScript({
return undefined;
}
+ /** The `#pageDescription` label of every clip of the page, if the page has one. */
+ function descriptionLabels(): Record<string, string> {
+ const description = getPageDescription();
+ return description ? { pageDescription: description } : {};
+ }
+
function getRectangleArea() {
return new Promise<Rect | null>((resolve) => {
const overlay = document.createElement('div');
@@ -289,7 +295,9 @@ export default defineContentScript({
title: pageTitle(),
content: container.innerHTML,
images,
- pageUrl: getPageLocationOrigin() + location.pathname + location.search + location.hash
+ pageUrl: getPageLocationOrigin() + location.pathname + location.search
+ + location.hash,
+ labels: descriptionLabels()
};
}
@@ -306,7 +314,7 @@ export default defineContentScript({
const images = getImages(body);
- const labels = {};
+ const labels = descriptionLabels();
const dates = getDocumentDates();
if (dates.publishedDate) {
labels['publishedDate'] = dates.publishedDate.toISOString().substring(0, 10);
diff --git a/apps/web-clipper/entrypoints/popup/main.tsx b/apps/web-clipper/entrypoints/popup/main.tsx
index 77f3048448..8c20e15685 100644
--- a/apps/web-clipper/entrypoints/popup/main.tsx
+++ b/apps/web-clipper/entrypoints/popup/main.tsx
@@ -41,6 +41,7 @@ interface SelectedContent {
content: string;
images: { imageId: string, src: string }[];
pageUrl: string;
+ labels?: Record<string, string>;
}
/** The readable page, as the content script extracts it. */
@@ -316,6 +317,7 @@ function PagePreview({ tab, disabled, shortcuts, draft, onDraftChange }: {
const clip = mode === "selection" ? selection : mode === "page" ? article : undefined;
const shownTitle = title ?? (article ?? selection)?.title ?? tab?.title ?? "";
const shownDescription = description ?? tab?.description;
+ const savedDescription = shownDescription?.replace(/\s+/g, " ").trim();
useEffect(() => {
if (mode === "note") textAreaRef.current?.focus();
@@ -324,18 +326,20 @@ function PagePreview({ tab, disabled, shortcuts, draft, onDraftChange }: {
/** Keeps the popup open when the note could not be saved, so its text is not lost. */
async function saveNote() {
const content = text.trim();
- const pageDescription = shownDescription?.replace(/\s+/g, " ").trim();
const result = await sendMessage({
name: "save-link-with-note",
title: shownTitle.trim(),
content: content ? textToHtml(content) : "",
- ...(pageDescription && { description: pageDescription })
+ ...(savedDescription && { description: savedDescription })
});
if (result) window.close();
}
function saveClip(content: SelectedContent) {
- const titled = { ...content, title: shownTitle.trim() || content.title };
+ const labels = savedDescription === undefined
+ ? content.labels
+ : withDescription(content.labels, savedDescription);
+ const titled = { ...content, title: shownTitle.trim() || content.title, ...(labels && { labels }) };
void sendMessage(mode === "selection"
? { name: "save-selection", selection: titled }
: { name: "save-whole-page", page: titled });
@@ -380,6 +384,16 @@ function PagePreview({ tab, disabled, shortcuts, draft, onDraftChange }: {
{new URL(pageUrl).hostname}{published && ` · Published ${published}`}
</div>
)}
+ {shownDescription !== undefined && (
+ <textarea
+ className="page-description"
+ aria-label="Page description"
+ rows={2}
+ value={shownDescription}
+ onInput={(e) => onDraftChange({ ...draft, description: e.currentTarget.value })}
+ onKeyDown={saveNoteOnCtrlEnter}
+ />
+ )}
</div>
</div>
)}
@@ -398,17 +412,6 @@ function PagePreview({ tab, disabled, shortcuts, draft, onDraftChange }: {
<div className="clip-hint">This page has no article; save it as a bookmark.</div>
)}
- {mode === "note" && shownDescription !== undefined && (
- <textarea
- className="page-description"
- aria-label="Page description"
- rows={2}
- value={shownDescription}
- onInput={(e) => onDraftChange({ ...draft, description: e.currentTarget.value })}
- onKeyDown={saveNoteOnCtrlEnter}
- />
- )}
-
<div className="page-body">
{mode === "note" && (
<textarea
@@ -438,6 +441,12 @@ function PagePreview({ tab, disabled, shortcuts, draft, onDraftChange }: {
);
}
+/** A clip's labels with `#pageDescription` as the user left it, or without one when it was cleared. */
+function withDescription(labels: Record<string, string> | undefined, description: string) {
+ const { pageDescription: _, ...others } = labels ?? {};
+ return description ? { ...others, pageDescription: description } : others;
+}
+
/** The modes the page offers, the default first: the selection, then the article, then a note. */
function availableModes(article: ExtractedPage | undefined, selection: SelectedContent | undefined): ClipMode[] {
const modes: ClipMode[] = [];
diff --git a/apps/web-clipper/entrypoints/popup/popup.spec.tsx b/apps/web-clipper/entrypoints/popup/popup.spec.tsx
index eb039e66e0..d2556a2ce5 100644
--- a/apps/web-clipper/entrypoints/popup/popup.spec.tsx
+++ b/apps/web-clipper/entrypoints/popup/popup.spec.tsx
@@ -371,20 +371,31 @@ describe("popup", () => {
expect(closeWindow).toHaveBeenCalledOnce();
});
- it("shows the page's description in a bookmark, and saves it as edited", async () => {
+ it("shows the page's description under the title in every mode, and saves it as edited", async () => {
metadata = { description: "All about the post" };
+ selection = SELECTION;
await rerender();
- expect(container.querySelector(".page-description")).toBeNull();
+ const description = () => container.querySelector<HTMLTextAreaElement>(".page-heading .page-description");
+ expect(description()?.value).toBe("All about the post");
+ expect(description()?.getAttribute("aria-label")).toBe("Page description");
+ expect(cardParts()).toEqual([ "page-heading", "clip-mode", "page-body", "btn btn-primary primary-action" ]);
- await click("Bookmark");
- expect(cardParts()).toEqual([
- "page-heading", "clip-mode", "page-description", "page-body", "btn btn-primary primary-action"
- ]);
- const description = container.querySelector<HTMLTextAreaElement>(".page-description");
- expect(description?.value).toBe("All about the post");
- expect(description?.getAttribute("aria-label")).toBe("Page description");
+ await click("Save selection");
+ expect(sendMessage).toHaveBeenLastCalledWith({
+ name: "save-selection",
+ selection: { ...SELECTION, title: "An article", labels: { pageDescription: "All about the post" } }
+ });
+ await click("Page");
await type(".page-description", " Edited\n description ");
+ await click("Save page to Trilium");
+ expect(sendMessage).toHaveBeenLastCalledWith({
+ name: "save-whole-page",
+ page: { ...PAGE, labels: { publishedDate: "2024-05-01", pageDescription: "Edited description" } }
+ });
+
+ await click("Bookmark");
+ expect(description()?.value).toBe(" Edited\n description ");
sendMessage.mockResolvedValueOnce(undefined);
await ctrlEnter(".page-description");
expect(sendMessage).toHaveBeenLastCalledWith({
@@ -396,15 +407,22 @@ describe("popup", () => {
// A cleared description stays in the card while it is edited, and is not saved.
await type(".page-description", " ");
- expect(container.querySelector(".page-description")).not.toBeNull();
+ expect(description()).not.toBeNull();
await click("Save bookmark");
expect(sendMessage).toHaveBeenLastCalledWith({ name: "save-link-with-note", title: "An article", content: "" });
+ await click("Page");
+ await click("Save page to Trilium");
+ expect(sendMessage).toHaveBeenLastCalledWith({
+ name: "save-whole-page",
+ page: { ...PAGE, labels: { publishedDate: "2024-05-01" } }
+ });
});
it("shows no description where the page gives none or cannot be asked for one", async () => {
// An outdated content script answers nothing.
metadata = undefined;
await rerender();
+ expect(container.querySelector(".page-description")).toBeNull();
await click("Bookmark");
expect(container.querySelector(".page-description")).toBeNull();
diff --git a/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md b/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md
index 8907fb23c5..d89a44f195 100644
--- a/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md
+++ b/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md
@@ -29,11 +29,13 @@ The extension is available from the official browser web stores:
Clicking the extension's button in the browser toolbar opens its popup:
-* The popup shows what will be saved from the current page: the note's title, which can be edited before saving, the website, and below them a preview. A switch above the preview chooses what to save, among what the page offers:
+* The popup shows what will be saved from the current page: the note's title, which can be edited before saving, the website, the page's description if it has one, and below them a preview. A switch above the preview chooses what to save, among what the page offers:
* _Selection_, when text is selected on the page: _Save selection_ saves it into the note of that page's clippings, as the context menu does.
* _Page_, when the page has an article: _Save page to Trilium_ saves the article's text and images, and the publication date shows next to the website when the page states one.
- * _Bookmark_, always: a text box for a note about the page replaces the preview, and _Save bookmark_ (or <kbd>Ctrl</kbd>+<kbd>Enter</kbd>) saves a link to the page with that note. Left empty, the title stays the page's title. If the page describes itself (in its `description` meta tag, or the one it gives social sites), the description is shown above the text box, where it can be edited or cleared, and is saved in the note's `#pageDescription` label. The label is updated when the page is bookmarked again.
+ * _Bookmark_, always: a text box for a note about the page replaces the preview, and _Save bookmark_ (or <kbd>Ctrl</kbd>+<kbd>Enter</kbd>) saves a link to the page with that note. Left empty, the title stays the page's title.
+
+ The description comes from the page's `description` meta tag, or the one it gives social sites. It can be edited or cleared before saving, and is saved in the `#pageDescription` label of the note. Clippings saved with the keyboard shortcuts or the context menu, screenshots and images included, get the description as the page gives it. Each clipping that brings a description updates the label.
The popup opens on the selection if there is one, otherwise on the article. On a page with no article (Readability cannot find one) and no selection, it opens on _Bookmark_ and says the page has no article. The keyboard shortcuts and the context menu still save right away, without a preview.
* Pages the extension cannot access (the browser's own pages, the extension stores, and pages that were open before the extension was installed until they are reloaded) cannot be saved or captured, so the popup says so in place of the preview, and only _Tabs_ remains available there.
@@ -54,6 +56,8 @@ Further clippings of the same kind from the same page are added to the note crea
A YouTube video embedded in a clipped page is saved as a <a class="reference-link" href="../Note%20Types/Text/Link%20Previews.md">Link Previews</a> embed, with the video's title and thumbnail. As with a link preview added in the editor, the video plays only when clicked. Other embedded content (such as videos from other websites) is not saved.
+The popup's preview shows each such video as a chip with the YouTube icon and the video's short link, and leaves out the embedded content that will not be saved.
+
## Keyboard shortcuts
Keyboard shortcuts are available for most functions: