Skip to content

Build your personal knowledge base with Trilium Notes

feat(clipper): save the page's description with a bookmark (#802)

Elian Doran99a1c9838859
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 1224e2e4e3..8f4c2f8b29 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
@@ -43,7 +43,10 @@
<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.</li>
+ 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>
</ul>
<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,
diff --git a/apps/server/src/routes/api/clipper.spec.ts b/apps/server/src/routes/api/clipper.spec.ts
index bbd070ff4a..88e0c080c8 100644
--- a/apps/server/src/routes/api/clipper.spec.ts
+++ b/apps/server/src/routes/api/clipper.spec.ts
@@ -119,10 +119,15 @@ describe("clipper route handlers", () => {
images: [],
clipType: "note",
pageUrl: "https://example.com/page",
- labels: { source: "web" }
+ labels: {
+ source: "web",
+ pageDescription: "Tom & <b>Jerry</b><script>alert(1)</script>"
+ }
}
} as unknown as Request));
- expect(result.noteId).toBeTruthy();
+ const note = becca.getNoteOrThrow(result.noteId);
+ expect(note.getLabelValue("source")).toBe("web");
+ expect(note.getLabelValue("pageDescription")).toBe("Tom & Jerry");
});
it("clips to the top level when there is no clipper inbox and no journal", async () => {
diff --git a/apps/server/src/routes/api/clipper.ts b/apps/server/src/routes/api/clipper.ts
index 5603ae431f..06a5e33745 100644
--- a/apps/server/src/routes/api/clipper.ts
+++ b/apps/server/src/routes/api/clipper.ts
@@ -114,8 +114,7 @@ async function createNote(req: Request) {
if (labels) {
for (const labelName in labels) {
- const labelValue = sanitize.sanitizeHtml(labels[labelName]);
- note.setLabel(labelName, labelValue);
+ note.setLabel(labelName, sanitizeLabelValue(labels[labelName]));
}
}
@@ -134,6 +133,15 @@ async function createNote(req: Request) {
};
}
+/**
+ * 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.
+ */
+function sanitizeLabelValue(value: string) {
+ return sanitize.sanitizeHtmlCustom(value, { allowedTags: [], allowedAttributes: {} })
+ .replaceAll("&amp;", "&");
+}
+
export async function processContent(images: Image[], note: BNote, content: string) {
let rewrittenContent = sanitize.sanitizeHtml(content);
diff --git a/apps/web-clipper/entrypoints/background/index.spec.ts b/apps/web-clipper/entrypoints/background/index.spec.ts
index b33f88a7dd..93cd981212 100644
--- a/apps/web-clipper/entrypoints/background/index.spec.ts
+++ b/apps/web-clipper/entrypoints/background/index.spec.ts
@@ -613,6 +613,17 @@ describe("background", () => {
expect(lastPayload()).toMatchObject({ title: "" });
});
+ it("labels a bookmark with the description the popup sends", async () => {
+ const save = (description?: string) => sendRuntimeMessage(
+ { name: "save-link-with-note", title: "T", content: "", description });
+
+ await save("About the page");
+ expect(lastPayload()).toMatchObject({ labels: { pageDescription: "About the page" } });
+
+ await save();
+ expect(lastPayload()).not.toHaveProperty("labels");
+ });
+
it("opens a note in the browser when the desktop app cannot", async () => {
const create = vi.fn(async (_properties: { url: string }) => ({}));
Object.assign(fakeBrowser.tabs, { create });
diff --git a/apps/web-clipper/entrypoints/background/index.ts b/apps/web-clipper/entrypoints/background/index.ts
index a48c746425..8b2da8e5a8 100644
--- a/apps/web-clipper/entrypoints/background/index.ts
+++ b/apps/web-clipper/entrypoints/background/index.ts
@@ -326,7 +326,7 @@ export default defineBackground(() => {
toast(savedMessage("Page", failedImages), resp.noteId);
}
- async function saveLinkWithNote(title: string, content: string) {
+ async function saveLinkWithNote(title: string, content: string, description?: string) {
const activeTab = await getActiveTab();
if (!title.trim()) {
@@ -337,7 +337,8 @@ export default defineBackground(() => {
title,
content,
clipType: 'note',
- pageUrl: activeTab.url
+ pageUrl: activeTab.url,
+ ...(description && { labels: { pageDescription: description } })
});
toast("Link with note has been saved to Trilium.", resp.noteId);
@@ -466,7 +467,7 @@ export default defineBackground(() => {
return await saveSelection(request.selection);
}
else if (request.name === 'save-link-with-note') {
- return await saveLinkWithNote(request.title, request.content);
+ return await saveLinkWithNote(request.title, request.content, request.description);
}
else if (request.name === 'save-tabs') {
return await saveTabs();
diff --git a/apps/web-clipper/entrypoints/content/index.spec.ts b/apps/web-clipper/entrypoints/content/index.spec.ts
index 0eb313541e..be501aca13 100644
--- a/apps/web-clipper/entrypoints/content/index.spec.ts
+++ b/apps/web-clipper/entrypoints/content/index.spec.ts
@@ -149,6 +149,27 @@ describe("content script", () => {
});
});
+ describe("page metadata", () => {
+ it("reads the description from the first description tag that has one", async () => {
+ const getMetadata = () => send({ name: "trilium-get-page-metadata" });
+ document.head.innerHTML = `
+ <meta name="twitter:description" content="From Twitter">
+ <meta property="og:description" content="From Open Graph">
+ <meta name="description" content=" Spread
+ over lines ">`;
+ expect(await getMetadata()).toEqual({ description: "Spread over lines" });
+
+ document.querySelector("meta[name='description']")?.remove();
+ expect(await getMetadata()).toEqual({ description: "From Open Graph" });
+
+ document.querySelector("meta[property='og:description']")?.setAttribute("content", " ");
+ expect(await getMetadata()).toEqual({ description: "From Twitter" });
+
+ document.head.innerHTML = "<meta name=\"description\">";
+ expect(await getMetadata()).toEqual({});
+ });
+ });
+
describe("screenshot area", () => {
it("returns the dragged rectangle once the overlay is gone", async () => {
vi.useFakeTimers();
diff --git a/apps/web-clipper/entrypoints/content/index.ts b/apps/web-clipper/entrypoints/content/index.ts
index 44258aaf57..114d18ff9f 100644
--- a/apps/web-clipper/entrypoints/content/index.ts
+++ b/apps/web-clipper/entrypoints/content/index.ts
@@ -50,6 +50,21 @@ export default defineContentScript({
return { publishedDate, modifiedDate };
}
+ /** The page's own summary, preferred to the one it gives social sites, on a single line. */
+ function getPageDescription() {
+ const selectors = [
+ "meta[name='description']",
+ "meta[property='og:description']",
+ "meta[name='twitter:description']"
+ ];
+ for (const selector of selectors) {
+ const description = document.querySelector(selector)?.getAttribute("content")
+ ?.replace(/\s+/g, " ").trim();
+ if (description) return description;
+ }
+ return undefined;
+ }
+
function getRectangleArea() {
return new Promise<Rect | null>((resolve) => {
const overlay = document.createElement('div');
@@ -309,6 +324,9 @@ export default defineContentScript({
labels
};
}
+ else if (message.name === "trilium-get-page-metadata") {
+ return { description: getPageDescription() };
+ }
else {
throw new Error(`Unknown command: ${ JSON.stringify(message)}`);
}
diff --git a/apps/web-clipper/entrypoints/popup/main.tsx b/apps/web-clipper/entrypoints/popup/main.tsx
index d376db8bed..77f3048448 100644
--- a/apps/web-clipper/entrypoints/popup/main.tsx
+++ b/apps/web-clipper/entrypoints/popup/main.tsx
@@ -60,6 +60,8 @@ interface TabContent {
/** The tab's own title and address, which a note clip saves. */
title?: string;
url?: string;
+ /** What the page says about itself, which a note clip saves in its `#pageDescription` label. */
+ description?: string;
}
/**
@@ -73,6 +75,8 @@ interface Draft {
mode?: ClipMode;
/** `undefined` until the user edits the title. */
title?: string;
+ /** `undefined` until the user edits the page's description. */
+ description?: string;
text: string;
}
@@ -302,7 +306,7 @@ function PagePreview({ tab, disabled, shortcuts, draft, onDraftChange }: {
draft: Draft;
onDraftChange: (draft: Draft) => void;
}) {
- const { mode: chosenMode, title, text } = draft;
+ const { mode: chosenMode, title, description, text } = draft;
const textAreaRef = useRef<HTMLTextAreaElement>(null);
const article = typeof tab?.page === "object" ? tab.page : undefined;
@@ -311,6 +315,7 @@ function PagePreview({ tab, disabled, shortcuts, draft, onDraftChange }: {
const mode = chosenMode && modes.includes(chosenMode) ? chosenMode : modes[0];
const clip = mode === "selection" ? selection : mode === "page" ? article : undefined;
const shownTitle = title ?? (article ?? selection)?.title ?? tab?.title ?? "";
+ const shownDescription = description ?? tab?.description;
useEffect(() => {
if (mode === "note") textAreaRef.current?.focus();
@@ -319,10 +324,12 @@ 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) : ""
+ content: content ? textToHtml(content) : "",
+ ...(pageDescription && { description: pageDescription })
});
if (result) window.close();
}
@@ -391,6 +398,17 @@ 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
@@ -485,8 +503,10 @@ async function readActiveTab(): Promise<TabContent> {
const [ tab ] = await browser.tabs.query({ active: true, currentWindow: true });
if (tab?.id === undefined) return { page: "inaccessible", selection: null };
- const [ page, selection ] = await Promise.all([ extractPage(tab.id), readSelection(tab.id) ]);
- return { page, selection, title: tab.title, url: tab.url };
+ const [ page, selection, description ] = await Promise.all([
+ extractPage(tab.id), readSelection(tab.id), readDescription(tab.id)
+ ]);
+ return { page, selection, title: tab.title, url: tab.url, description };
}
/**
@@ -517,6 +537,20 @@ async function readSelection(tabId: number): Promise<SelectedContent | null> {
}
}
+/**
+ * The page's description, or `undefined` when it has none. A content script from before an update
+ * answers nothing, and none runs on the browser's own pages.
+ */
+async function readDescription(tabId: number): Promise<string | undefined> {
+ try {
+ const metadata: { description?: string } | undefined =
+ await browser.tabs.sendMessage(tabId, { name: "trilium-get-page-metadata" });
+ return metadata?.description;
+ } catch {
+ return undefined;
+ }
+}
+
/** A standalone document showing the page's content, its images loaded from the website. */
export function previewDocument({ content, images }: Pick<ExtractedPage, "content" | "images">) {
const doc = new DOMParser().parseFromString(content, "text/html");
diff --git a/apps/web-clipper/entrypoints/popup/popup.css b/apps/web-clipper/entrypoints/popup/popup.css
index 3387354d3d..e0ff50729e 100644
--- a/apps/web-clipper/entrypoints/popup/popup.css
+++ b/apps/web-clipper/entrypoints/popup/popup.css
@@ -172,6 +172,19 @@ body {
}
}
+ .page-description {
+ --input-background-color: transparent;
+
+ display: block;
+ width: 100%;
+ padding: 2px 6px;
+ border: 0;
+ border-radius: 6px;
+ color: var(--muted-text-color);
+ font-size: 0.85em;
+ resize: none;
+ }
+
.clip-hint {
padding-inline: 6px;
color: var(--muted-text-color);
diff --git a/apps/web-clipper/entrypoints/popup/popup.spec.tsx b/apps/web-clipper/entrypoints/popup/popup.spec.tsx
index 00327f5904..eb039e66e0 100644
--- a/apps/web-clipper/entrypoints/popup/popup.spec.tsx
+++ b/apps/web-clipper/entrypoints/popup/popup.spec.tsx
@@ -36,8 +36,16 @@ const SELECTION = {
};
/** What the content script answers to `trilium-save-selection`; nothing is selected unless a test says so. */
let selection: unknown;
-const tabsSendMessage = vi.fn(async (_tabId: number, message: { name: string }): Promise<unknown> =>
- message.name === "trilium-save-page" ? PAGE : selection);
+/** What the content script answers to `trilium-get-page-metadata`, or the error it fails with; no description unless a test says so. */
+let metadata: unknown;
+const tabsSendMessage = vi.fn(async (_tabId: number, message: { name: string }): Promise<unknown> => {
+ if (message.name === "trilium-save-page") return PAGE;
+ if (message.name === "trilium-get-page-metadata") {
+ if (metadata instanceof Error) throw metadata;
+ return metadata;
+ }
+ return selection;
+});
const closeWindow = vi.fn();
let container: HTMLElement;
@@ -45,6 +53,7 @@ describe("popup", () => {
beforeEach(async () => {
fakeBrowser.reset();
selection = undefined;
+ metadata = {};
Object.assign(fakeBrowser.runtime, { sendMessage, openOptionsPage });
Object.assign(fakeBrowser.commands, { getAll: getAllCommands });
Object.assign(fakeBrowser.tabs, { query: tabsQuery, sendMessage: tabsSendMessage });
@@ -271,7 +280,7 @@ describe("popup", () => {
tabsQuery.mockResolvedValueOnce([ {} ]);
await rerender();
expect(unavailable()).toContain("The extension cannot access this page.");
- expect(tabsSendMessage).toHaveBeenCalledTimes(4);
+ expect(tabsSendMessage).toHaveBeenCalledTimes(6);
});
it("previews the selection first, and switches to the whole page", async () => {
@@ -362,6 +371,50 @@ describe("popup", () => {
expect(closeWindow).toHaveBeenCalledOnce();
});
+ it("shows the page's description in a bookmark, and saves it as edited", async () => {
+ metadata = { description: "All about the post" };
+ await rerender();
+ expect(container.querySelector(".page-description")).toBeNull();
+
+ 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 type(".page-description", " Edited\n description ");
+ sendMessage.mockResolvedValueOnce(undefined);
+ await ctrlEnter(".page-description");
+ expect(sendMessage).toHaveBeenLastCalledWith({
+ name: "save-link-with-note",
+ title: "An article",
+ content: "",
+ description: "Edited description"
+ });
+
+ // 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();
+ await click("Save bookmark");
+ expect(sendMessage).toHaveBeenLastCalledWith({ name: "save-link-with-note", title: "An article", content: "" });
+ });
+
+ 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();
+ await click("Bookmark");
+ expect(container.querySelector(".page-description")).toBeNull();
+
+ metadata = new Error("Could not establish connection.");
+ await rerender();
+ await click("Bookmark");
+ expect(container.querySelector(".page-description")).toBeNull();
+ expect(container.querySelector(".page-body textarea")).not.toBeNull();
+ });
+
it("keeps a draft bookmark while Trilium is briefly not found", async () => {
await click("Bookmark");
await type(".page-title", "My title");
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 9cb863dea0..fcf734344b 100644
--- a/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md
+++ b/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md
@@ -33,7 +33,7 @@ Clicking the extension's button in the browser toolbar opens its popup:
* _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.
+ * _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.
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.