Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(clipper): load Readability only when a page is read
Elian Doran75a5123f0005
diff --git a/.claude/skills/developing-web-clipper/SKILL.md b/.claude/skills/developing-web-clipper/SKILL.mdindex 65bc030e5c..ef754a1e45 100644--- a/.claude/skills/developing-web-clipper/SKILL.md+++ b/.claude/skills/developing-web-clipper/SKILL.md@@ -1,6 +1,6 @@---name: developing-web-clipper-description: Use when working on Trilium's browser extension, the web clipper (`apps/web-clipper`, built with WXT for Chrome MV3 and Firefox MV2) — its background script, content script (Readability, screenshots, toasts), the Preact popup and options page, `wxt.config.ts` (manifest, keyboard `commands`, the Firefox sources zip), or the server side it talks to (`apps/server/src/routes/api/clipper.ts`, `/api/login/token`, the desktop port). Covers the message protocol between the extension's parts, how it finds and authenticates to Trilium, the compatibility rule with older Trilium versions, styling the pages in the Next theme from the client's own stylesheets, running and building it, the `fakeBrowser` spec patterns and the 100% coverage gate, and the traps already hit (undeclared commands, image placeholders, `$&` in `replaceAll()` replacements, `javascript:` links, the sources zip).+description: Use when working on Trilium's browser extension, the web clipper (`apps/web-clipper`, built with WXT for Chrome MV3 and Firefox MV2) — its background script, content script (selection, screenshots, toasts), the injected Readability script, the Preact popup and options page, `wxt.config.ts` (manifest, keyboard `commands`, the Firefox sources zip), or the server side it talks to (`apps/server/src/routes/api/clipper.ts`, `/api/login/token`, the desktop port). Covers the message protocol between the extension's parts, how it finds and authenticates to Trilium, the compatibility rule with older Trilium versions, styling the pages in the Next theme from the client's own stylesheets, running and building it, the `fakeBrowser` spec patterns and the 100% coverage gate, and the traps already hit (undeclared commands, image placeholders, `$&` in `replaceAll()` replacements, `javascript:` links, the sources zip).---# Developing the web clipper@@ -17,7 +17,8 @@ repository.|---|---|---|| `entrypoints/background/index.ts` | service worker (MV3) / background page (MV2) | context menus, keyboard commands, every save, image download, toasts || `entrypoints/background/trilium_server_facade.ts` | background | finds Trilium, authenticates, `callService()` |-| `entrypoints/content/index.ts` | every page (`<all_urls>`) | Readability extraction, selection, crop overlay, toast UI |+| `entrypoints/content/index.ts` | every page (`<all_urls>`) | selection, page description, crop overlay, toast UI |+| `entrypoints/readability/index.ts` | the tab, injected on demand | Readability extraction of the whole page; its `main()` value is the `executeScript()` result || `entrypoints/popup/main.tsx` | the toolbar popup | Preact `Popup`: capture buttons, link-with-note form, connection status || `entrypoints/options/main.tsx` | the options page | Preact `Options`: desktop port, server login || `entrypoints/offscreen/` | MV3 only (Chrome) | crops screenshots on a canvas, since an MV3 service worker has no DOM |@@ -32,11 +33,17 @@ Everything goes through `browser.runtime.sendMessage` / `browser.tabs.sendMessag- **background → popup:** `trilium-search-status` (`triliumSearch: TriliumSearchStatus`, whichstarts as `searching`) and `trilium-previously-visited` (`searchNote`). Both typesare exported from `trilium_server_facade.ts`; the popup imports them.-- **background → content script:** `trilium-save-selection`, `trilium-save-page`,+- **background → content script:** `trilium-save-selection`,`trilium-get-rectangle-for-screenshot` (the content script answers with the payload), and `toast`(`message`, `noteId`, `tabIds`).- **background → offscreen:** `{ type: "CROP_IMAGE" }`, the one message keyed by `type`.+The readable page is not a message: the popup and the background call `extractReadablePage(tabId)`+(`utils.ts`), which injects `/readability.js` with `browser.scripting.executeScript()` (the+`scripting` permission, in both builds), so Readability stays out of the content script that loads+on every page. Specs mock it with `Object.assign(fakeBrowser, { scripting: { executeScript } })`,+answering `[ { result: page } ]`.+Every user action in the background runs inside `showFailures()`, which turns an exception into atoast. A new action belongs inside it too, or it fails silently. A toast cannot show on browserpages or the extension stores, where no content script runs.diff --git a/apps/web-clipper/entrypoints/background/index.spec.ts b/apps/web-clipper/entrypoints/background/index.spec.tsindex 2b9890e4e9..03b7fea9ab 100644--- a/apps/web-clipper/entrypoints/background/index.spec.ts+++ b/apps/web-clipper/entrypoints/background/index.spec.ts@@ -56,6 +56,9 @@ let tabs: Tab[];let tabMessageHandler: (message: { name: string }) => unknown;const tabsSendMessage = vi.fn((_tabId: number, message: { name: string }) => Promise.resolve(tabMessageHandler(message)));+/** What `readability.js` returns in the active tab; no article unless a test says so. */+let readablePage: unknown;+const executeScript = vi.fn(async () => [ { result: readablePage } ]);const contextMenusCreate = vi.fn();const contextMenusRemoveAll = vi.fn(async () => {});const getContexts = vi.fn(async (): Promise<unknown[]> => []);@@ -69,6 +72,7 @@ describe("background", () => {fakeBrowser.reset();tabs = [ ACTIVE_TAB ];tabMessageHandler = () => undefined;+ readablePage = undefined;facade.callService.mockResolvedValue({ noteId: "saved" });vi.stubGlobal("fetch", fetchMock);vi.spyOn(console, "log").mockImplementation(() => {});@@ -95,7 +99,7 @@ describe("background", () => {captureVisibleTab: async () => PNG});Object.assign(fakeBrowser.runtime, { getContexts, sendMessage: runtimeSendMessage });- Object.assign(fakeBrowser, { offscreen: { createDocument } });+ Object.assign(fakeBrowser, { offscreen: { createDocument }, scripting: { executeScript } });background.main();await vi.waitFor(() => expect(contextMenusCreate).toHaveBeenCalledTimes(6));@@ -273,12 +277,14 @@ describe("background", () => {describe("saving the whole page", () => {it("saves the readable page from the shortcut, the menu and the popup", async () => {const page = { title: "Article", content: "<p>Body</p>", images: [], clipType: "page" };- tabMessageHandler = () => page;+ readablePage = page;await onCommand("saveWholePage");await onContextMenuClicked({ menuItemId: "trilium-save-page" });await sendRuntimeMessage({ name: "save-whole-page" });+ expect(executeScript).toHaveBeenCalledTimes(3);+ expect(executeScript).toHaveBeenCalledWith({ target: { tabId: 7 }, files: [ "/readability.js" ] });expect(facade.callService).toHaveBeenCalledTimes(3);expect(facade.callService).toHaveBeenLastCalledWith("POST", "notes", page);expect(await lastToast()).toMatchObject({ noteId: "saved" });@@ -289,6 +295,29 @@ describe("background", () => {expect(await lastToast()).toMatchObject(FAILURE_TOAST);});+ it("saves nothing from a page without an article or out of reach", async () => {+ await onCommand("saveWholePage");+ expect(await lastToast()).toMatchObject({+ ...GENERIC_FAILURE_TOAST,+ message: "Saving to Trilium failed: Trilium could not find an article on this page."+ });++ readablePage = { title: "Article", content: "<p>Body</p>", images: [] };+ tabs = [ { title: "Tab without id" } ];+ await onCommand("saveWholePage");++ tabs = [ ACTIVE_TAB ];+ executeScript.mockRejectedValueOnce(new Error("Cannot access a chrome:// URL"));+ await onCommand("saveWholePage");+ expect(await lastToast()).toMatchObject({+ ...GENERIC_FAILURE_TOAST,+ message: "Saving to Trilium failed: Cannot access a chrome:// URL"+ });++ expect(executeScript).toHaveBeenCalledTimes(2);+ expect(facade.callService).not.toHaveBeenCalled();+ });+it("saves the page the popup extracted, with the user's title, without reading it again", async () => {const page = {title: "Edited title",@@ -301,7 +330,7 @@ describe("background", () => {await sendRuntimeMessage({ name: "save-whole-page", page });- expect(tabsSendMessage).not.toHaveBeenCalledWith(7, { name: "trilium-save-page" });+ expect(executeScript).not.toHaveBeenCalled();expect(facade.callService).toHaveBeenCalledWith("POST", "notes", {...page,images: [ { ...page.images[0], dataUrl: expect.stringMatching(PNG_DATA_URL) } ]diff --git a/apps/web-clipper/entrypoints/background/index.ts b/apps/web-clipper/entrypoints/background/index.tsindex 5554990f7d..b954df4712 100644--- a/apps/web-clipper/entrypoints/background/index.ts+++ b/apps/web-clipper/entrypoints/background/index.ts@@ -1,4 +1,4 @@-import { randomString, type Rect } from "@/utils";+import { extractReadablePage, randomString, type Rect } from "@/utils";import setupContextMenu from "./context_menu";import TriliumServerFacade, { TriliumError } from "./trilium_server_facade";@@ -12,8 +12,6 @@ type BackgroundMessage = {name: "trilium-save-selection";} | {name: "trilium-get-rectangle-for-screenshot";-} | {- name: "trilium-save-page";} | {name: "trilium-get-page-metadata";};@@ -334,7 +332,7 @@ export default defineBackground(() => {/** Saves the readable page, or the page the popup already extracted and the user edited. */async function saveWholePage(page?: object) {- const payload = page ?? await requestFromPage({name: 'trilium-save-page'});+ const payload = page ?? await readActivePage();const failedImages = await postProcessImages(payload);@@ -343,6 +341,15 @@ export default defineBackground(() => {toast(savedMessage("Page", failedImages), resp.noteId);}+ async function readActivePage() {+ const activeTab = await getActiveTab();+ const page = activeTab.id === undefined ? undefined : await extractReadablePage(activeTab.id);+ if (!page) {+ throw new Error("Trilium could not find an article on this page.");+ }+ return page;+ }+async function saveLinkWithNote(title: string, content: string, description?: string) {const activeTab = await getActiveTab();diff --git a/apps/web-clipper/entrypoints/content/index.spec.ts b/apps/web-clipper/entrypoints/content/index.spec.tsindex 5220a07757..2c686ae5b2 100644--- a/apps/web-clipper/entrypoints/content/index.spec.ts+++ b/apps/web-clipper/entrypoints/content/index.spec.ts@@ -15,10 +15,6 @@ type Clipping = {labels: Record<string, string>};-const PARAGRAPH = "Trilium is a hierarchical note taking application with focus on "- + "building large personal knowledge bases. It supports rich text, code, canvas and many "- + "other note types, scripting and sync. ";-describe("content script", () => {beforeAll(() => {contentScript.main(undefined as never);@@ -109,57 +105,6 @@ describe("content script", () => {});});- describe("saving the page", () => {- it("returns the readable article with its publication dates as labels", async () => {- 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="og:description" content="About the article">`;- document.body.innerHTML = `- <nav><a href="/">Home</a></nav>- <article>- <h1>Article title</h1>- <p>${PARAGRAPH.repeat(3)}<a href="/docs">Docs</a>- <a href="mailto:[email protected]">Jane</a></p>- <p>${PARAGRAPH.repeat(3)}</p>- <img src="figure.png">- <p>${PARAGRAPH.repeat(3)}</p>- </article>`;-- const response = await send<Record<string, unknown>>({ name: "trilium-save-page" });-- expect(response).toMatchObject({- title: "Article title",- pageUrl: "https://example.com/blog/post.html?id=1",- clipType: "page",- 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"- } ]- });- expect(response.content).toContain("href=\"https://example.com/docs\"");- expect(response.content).toContain("href=\"mailto:[email protected]\"");- expect(response.content).not.toContain("Home");- expect(document.querySelector("nav")).not.toBeNull();- });-- 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<Clipping>({ name: "trilium-save-page" })).labels).toEqual({});-- document.body.innerHTML = "";- vi.spyOn(Document.prototype, "cloneNode")- .mockReturnValue(document.implementation.createHTMLDocument(""));- expect(await send({ name: "trilium-save-page" })).toBeUndefined();- });- });-describe("page metadata", () => {it("reads the description from the first description tag that has one", async () => {const getMetadata = () => send({ name: "trilium-get-page-metadata" });diff --git a/apps/web-clipper/entrypoints/content/index.ts b/apps/web-clipper/entrypoints/content/index.tsindex fe63561239..b1fcf67d65 100644--- a/apps/web-clipper/entrypoints/content/index.ts+++ b/apps/web-clipper/entrypoints/content/index.ts@@ -1,5 +1,7 @@-import { Readability } from "@mozilla/readability";-import { createLink, getPageLocationOrigin, randomString, type Rect } from "@/utils.js";+import {+ createLink, descriptionLabels, getImages, getPageDescription, getPageLocationOrigin,+ makeLinksAbsolute, type Rect+} from "@/utils.js";export default defineContentScript({matches: [@@ -12,65 +14,6 @@ export default defineContentScript({return titleElements[0]?.text.trim() ?? document.title.trim();}- function getReadableDocument() {- // Readability changes the document it parses, so it reads a copy of the page.- const documentCopy = document.cloneNode(true) as Document;- const readability = new Readability(documentCopy, {- // Returns the content as an element rather than as HTML.- serializer: (node) => node as HTMLElement- });-- const article = readability.parse();-- if (!article?.content) {- throw new Error('Could not parse HTML document with Readability');- }-- return {- title: article.title,- body: article.content,- };- }-- function getDocumentDates() {- let publishedDate: Date | null = null;- let modifiedDate: Date | null = null;-- const articlePublishedTime = document.querySelector("meta[property='article:published_time']")?.getAttribute('content');- if (articlePublishedTime) {- publishedDate = new Date(articlePublishedTime);- }-- const articleModifiedTime = document.querySelector("meta[property='article:modified_time']")?.getAttribute('content');- if (articleModifiedTime) {- modifiedDate = new Date(articleModifiedTime);- }-- // TODO: if we didn't get dates from meta, then try to get them from JSON-LD- 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;- }-- /** 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');@@ -198,44 +141,6 @@ export default defineContentScript({});}- function makeLinksAbsolute(container: HTMLElement) {- // `link.href` reads the URL the browser resolved against the page, and leaves- // `mailto:`, `tel:` and other non-web schemes unchanged.- for (const link of container.getElementsByTagName('a')) {- if (link.href) {- link.setAttribute("href", link.href);- }- }- }-- function getImages(container: HTMLElement) {- const images: {imageId: string, src: string}[] = [];-- for (const img of container.getElementsByTagName('img')) {- if (!img.src) {- continue;- }-- const existingImage = images.find(image => image.src === img.src);-- if (existingImage) {- img.src = existingImage.imageId;- }- else {- const imageId = randomString(20);-- images.push({- imageId,- src: img.src- });-- img.src = imageId;- }- }-- return images;- }-async function prepareMessageResponse(message: {name: string, noteId?: string, message?: string, tabIds?: string[]}) {console.info(`Message: ${ message.name}`);@@ -307,31 +212,6 @@ export default defineContentScript({devicePixelRatio: window.devicePixelRatio};}- else if (message.name === "trilium-save-page") {- const {title, body} = getReadableDocument();-- makeLinksAbsolute(body);-- const images = getImages(body);-- const labels = descriptionLabels();- const dates = getDocumentDates();- if (dates.publishedDate) {- labels['publishedDate'] = dates.publishedDate.toISOString().substring(0, 10);- }- if (dates.modifiedDate) {- labels['modifiedDate'] = dates.modifiedDate.toISOString().substring(0, 10);- }-- return {- title,- content: body.innerHTML,- images,- pageUrl: getPageLocationOrigin() + location.pathname + location.search,- clipType: 'page',- labels- };- }else if (message.name === "trilium-get-page-metadata") {return { description: getPageDescription() };}diff --git a/apps/web-clipper/entrypoints/popup/main.tsx b/apps/web-clipper/entrypoints/popup/main.tsxindex 6cd2565a73..31e5fcbf3c 100644--- a/apps/web-clipper/entrypoints/popup/main.tsx+++ b/apps/web-clipper/entrypoints/popup/main.tsx@@ -21,6 +21,8 @@ import type { ComponentChildren } from "preact";import { Fragment, render } from "preact";import { useEffect, useRef, useState } from "preact/hooks";+import { extractReadablePage, type ReadablePage } from "@/utils";+import type { TriliumSearchNoteStatus, TriliumSearchStatus } from "../background/trilium_server_facade";const HELP_URL = "https://docs.triliumnotes.org/user-guide/setup/web-clipper";@@ -47,14 +49,8 @@ interface SelectedContent {labels?: Record<string, string>;}-/** The readable page, as the content script extracts it. */-interface ExtractedPage extends SelectedContent {- clipType: "page";- labels: Record<string, string>;-}-/** The current page: its readable version, or why there is none. */-type PageState = ExtractedPage | "unreadable" | "inaccessible";+type PageState = ReadablePage | "unreadable" | "inaccessible";/** What the active tab offers to save. */interface TabContent {@@ -504,7 +500,7 @@ function fitToContent(frame: HTMLIFrameElement) {}/** 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[] {+function availableModes(article: ReadablePage | undefined, selection: SelectedContent | undefined): ClipMode[] {const modes: ClipMode[] = [];if (selection) modes.push("selection");if (article) modes.push("page");@@ -575,12 +571,12 @@ async function readActiveTab(): Promise<TabContent> {}/**- * The content script answers `undefined` when Readability cannot parse the page, and the message- * fails where no content script runs.+ * `extractReadablePage()` answers `undefined` when Readability cannot parse the page, and fails+ * where the extension cannot run scripts.*/async function extractPage(tabId: number): Promise<PageState> {try {- return await browser.tabs.sendMessage(tabId, { name: "trilium-save-page" }) ?? "unreadable";+ return await extractReadablePage(tabId) ?? "unreadable";} catch {return "inaccessible";}@@ -617,7 +613,7 @@ async function readDescription(tabId: number): Promise<string | undefined> {}/** A standalone document showing the page's content, its images loaded from the website. */-export function previewDocument({ content, images }: Pick<ExtractedPage, "content" | "images">) {+export function previewDocument({ content, images }: Pick<ReadablePage, "content" | "images">) {const doc = new DOMParser().parseFromString(content, "text/html");for (const img of doc.querySelectorAll("img")) {const image = images.find(({ imageId }) => imageId === img.getAttribute("src"));diff --git a/apps/web-clipper/entrypoints/popup/popup.spec.tsx b/apps/web-clipper/entrypoints/popup/popup.spec.tsxindex ff375089b6..c8063d6014 100644--- a/apps/web-clipper/entrypoints/popup/popup.spec.tsx+++ b/apps/web-clipper/entrypoints/popup/popup.spec.tsx@@ -27,6 +27,8 @@ const PAGE = {clipType: "page",labels: { publishedDate: "2024-05-01" }};+/** What `readability.js` returns in the tab, as `browser.scripting.executeScript()` answers. */+const executeScript = vi.fn(async (): Promise<unknown> => [ { result: PAGE } ]);const tabsQuery = vi.fn(async (): Promise<{ id?: number, title?: string, url?: string }[]> => [ { id: 7 } ]);const SELECTION = {title: "Page title",@@ -39,7 +41,6 @@ let selection: unknown;/** 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;@@ -57,6 +58,7 @@ describe("popup", () => {Object.assign(fakeBrowser.runtime, { sendMessage, openOptionsPage });Object.assign(fakeBrowser.commands, { getAll: getAllCommands });Object.assign(fakeBrowser.tabs, { query: tabsQuery, sendMessage: tabsSendMessage });+ Object.assign(fakeBrowser, { scripting: { executeScript } });vi.spyOn(window, "close").mockImplementation(closeWindow);vi.spyOn(console, "log").mockImplementation(() => {});@@ -205,7 +207,7 @@ describe("popup", () => {it("previews the readable page with its title, source and date", () => {expect(tabsQuery).toHaveBeenCalledWith({ active: true, currentWindow: true });- expect(tabsSendMessage).toHaveBeenCalledWith(7, { name: "trilium-save-page" });+ expect(executeScript).toHaveBeenCalledWith({ target: { tabId: 7 }, files: [ "/readability.js" ] });expect(cardParts()).toEqual([ "page-heading", "clip-mode", "page-body", "btn btn-primary primary-action" ]);expect(modes()).toEqual([ [ "Page", "true" ], [ "Bookmark", "false" ] ]);@@ -234,14 +236,14 @@ describe("popup", () => {});it("leaves out the date of a page that has none", async () => {- tabsSendMessage.mockResolvedValueOnce({ ...PAGE, labels: {} });+ executeScript.mockResolvedValueOnce([ { result: { ...PAGE, labels: {} } } ]);await rerender();expect(container.querySelector(".page-meta")?.textContent).toBe("example.com");});it("says so while the page is read", async () => {let resolvePage: (page: unknown) => void = () => {};- tabsSendMessage.mockReturnValueOnce(new Promise((resolve) => {+ executeScript.mockReturnValueOnce(new Promise((resolve) => {resolvePage = resolve;}));await rerender();@@ -249,13 +251,13 @@ describe("popup", () => {expect(cardParts()).toEqual([ "page-body", "btn btn-primary primary-action" ]);expect(button("Save page to Trilium")?.disabled).toBe(true);- resolvePage(PAGE);+ resolvePage([ { result: PAGE } ]);await flush();expect(container.querySelector(".page-body iframe")).not.toBeNull();});it("opens a page with no article on a bookmark, and keeps every other action", async () => {- tabsSendMessage.mockResolvedValueOnce(undefined);+ executeScript.mockResolvedValueOnce([ { result: null } ]);await rerender();expect(container.querySelector(".no-items")).toBeNull();expect(container.querySelector(".clip-mode")).toBeNull();@@ -267,9 +269,8 @@ describe("popup", () => {});it("keeps only the actions that need no access to a page out of reach", async () => {- tabsSendMessage- .mockRejectedValueOnce(new Error("Could not establish connection."))- .mockRejectedValueOnce(new Error("Could not establish connection."));+ executeScript.mockRejectedValueOnce(new Error("Cannot access a chrome:// URL"));+ tabsSendMessage.mockRejectedValueOnce(new Error("Could not establish connection."));await rerender();expect(unavailable()).toBe("The extension cannot access this page.\nIf it is a regular web page, reload it."@@ -282,7 +283,8 @@ describe("popup", () => {tabsQuery.mockResolvedValueOnce([ {} ]);await rerender();expect(unavailable()).toContain("The extension cannot access this page.");- expect(tabsSendMessage).toHaveBeenCalledTimes(6);+ expect(executeScript).toHaveBeenCalledTimes(2);+ expect(tabsSendMessage).toHaveBeenCalledTimes(4);});it("previews the selection first, and switches to the whole page", async () => {@@ -310,7 +312,7 @@ describe("popup", () => {it("saves the selection of a page that has no article, and ignores an empty one", async () => {selection = SELECTION;- tabsSendMessage.mockResolvedValueOnce(undefined);+ executeScript.mockResolvedValueOnce([ { result: null } ]);await rerender();expect(container.querySelector(".no-items")).toBeNull();expect(modes()).toEqual([ [ "Selection", "true" ], [ "Bookmark", "false" ] ]);@@ -609,6 +611,7 @@ describe("icons", () => {vi.spyOn(console, "log").mockImplementation(() => {});Object.assign(fakeBrowser.commands, { getAll: getAllCommands });Object.assign(fakeBrowser.tabs, { query: tabsQuery, sendMessage: tabsSendMessage });+ Object.assign(fakeBrowser, { scripting: { executeScript } });const container = document.createElement("div");await act(() => render(<Popup />, container));diff --git a/apps/web-clipper/entrypoints/readability/index.spec.ts b/apps/web-clipper/entrypoints/readability/index.spec.tsnew file mode 100644index 0000000000..8b876a7d35--- /dev/null+++ b/apps/web-clipper/entrypoints/readability/index.spec.ts@@ -0,0 +1,83 @@+import { Readability } from "@mozilla/readability";+import type { Window as HappyDOMWindow } from "happy-dom";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import type { ReadablePage } from "@/utils";++import readability from "./index";++const PARAGRAPH = "Trilium is a hierarchical note taking application with focus on "+ + "building large personal knowledge bases. It supports rich text, code, canvas and many "+ + "other note types, scripting and sync. ";++describe("readable page", () => {+ beforeEach(() => {+ (window as unknown as HappyDOMWindow).happyDOM.setURL("https://example.com/blog/post.html?id=1#comments");+ document.head.innerHTML = "<title> Post title </title>";+ document.body.innerHTML = "";+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it("returns the readable article with its publication dates as labels", () => {+ 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="og:description" content="About the article">`;+ document.body.innerHTML = `+ <nav><a href="/">Home</a></nav>+ <article>+ <h1>Article title</h1>+ <p>${PARAGRAPH.repeat(3)}<a href="/docs">Docs</a>+ <a href="mailto:[email protected]">Jane</a></p>+ <p>${PARAGRAPH.repeat(3)}</p>+ <img src="figure.png">+ <p>${PARAGRAPH.repeat(3)}</p>+ </article>`;++ const page = readPage();++ expect(page).toMatchObject({+ title: "Article title",+ pageUrl: "https://example.com/blog/post.html?id=1",+ clipType: "page",+ 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"+ } ]+ });+ expect(page?.content).toContain(`src="${page?.images[0]?.imageId}"`);+ expect(page?.content).toContain("href=\"https://example.com/docs\"");+ expect(page?.content).toContain("href=\"mailto:[email protected]\"");+ expect(page?.content).not.toContain("Home");+ expect(document.querySelector("nav")).not.toBeNull();+ });++ it("adds no labels without dates, and titles an untitled article after the document", () => {+ document.body.innerHTML = `<article><p>${PARAGRAPH.repeat(5)}</p></article>`;+ expect(readPage()?.labels).toEqual({});++ const content = document.createElement("div");+ vi.spyOn(Readability.prototype, "parse")+ .mockReturnValue({ title: null, content } as unknown as ReturnType<Readability["parse"]>);+ expect(readPage()?.title).toBe("Post title");+ });++ it("returns nothing when Readability finds no article", () => {+ vi.spyOn(Document.prototype, "cloneNode")+ .mockReturnValue(document.implementation.createHTMLDocument(""));+ expect(readPage()).toBeUndefined();+ });+});++function readPage() {+ return readability.main() as ReadablePage | undefined;+}diff --git a/apps/web-clipper/entrypoints/readability/index.ts b/apps/web-clipper/entrypoints/readability/index.tsnew file mode 100644index 0000000000..a2ee3ae862--- /dev/null+++ b/apps/web-clipper/entrypoints/readability/index.ts@@ -0,0 +1,65 @@+import { Readability } from "@mozilla/readability";++import {+ descriptionLabels, getImages, getPageLocationOrigin, makeLinksAbsolute, type ReadablePage+} from "@/utils";++/**+ * Extracts the readable page. `extractReadablePage()` injects it into the tab only when a page is+ * read, so Readability does not load with the content script on every page. The value `main()`+ * returns is the result of `executeScript()`.+ */+export default defineUnlistedScript(readPage);++function readPage(): ReadablePage | undefined {+ // Readability changes the document it parses, so it reads a copy of the page.+ const documentCopy = document.cloneNode(true) as Document;+ const article = new Readability(documentCopy, {+ // Returns the content as an element rather than as HTML.+ serializer: (node) => node as HTMLElement+ }).parse();++ if (!article?.content) {+ return undefined;+ }++ const body = article.content;+ makeLinksAbsolute(body);+ const images = getImages(body);++ const labels = descriptionLabels();+ const { publishedDate, modifiedDate } = getDocumentDates();+ if (publishedDate) {+ labels['publishedDate'] = publishedDate.toISOString().substring(0, 10);+ }+ if (modifiedDate) {+ labels['modifiedDate'] = modifiedDate.toISOString().substring(0, 10);+ }++ return {+ title: article.title ?? document.title,+ content: body.innerHTML,+ images,+ pageUrl: getPageLocationOrigin() + location.pathname + location.search,+ clipType: 'page',+ labels+ };+}++function getDocumentDates() {+ let publishedDate: Date | null = null;+ let modifiedDate: Date | null = null;++ const articlePublishedTime = document.querySelector("meta[property='article:published_time']")?.getAttribute('content');+ if (articlePublishedTime) {+ publishedDate = new Date(articlePublishedTime);+ }++ const articleModifiedTime = document.querySelector("meta[property='article:modified_time']")?.getAttribute('content');+ if (articleModifiedTime) {+ modifiedDate = new Date(articleModifiedTime);+ }++ // TODO: if we didn't get dates from meta, then try to get them from JSON-LD+ return { publishedDate, modifiedDate };+}diff --git a/apps/web-clipper/utils.spec.ts b/apps/web-clipper/utils.spec.tsindex 75aa7fd232..f5f68794eb 100644--- a/apps/web-clipper/utils.spec.ts+++ b/apps/web-clipper/utils.spec.ts@@ -2,7 +2,7 @@ import type { Window as HappyDOMWindow } from "happy-dom";import { afterEach, describe, expect, it, vi } from "vitest";import { fakeBrowser } from "wxt/testing/fake-browser";-import { createLink, getPageLocationOrigin, randomString } from "./utils";+import { createLink, extractReadablePage, getPageLocationOrigin, randomString } from "./utils";describe("randomString", () => {it("returns alphanumeric strings of the requested length", () => {@@ -40,6 +40,27 @@ describe("createLink", () => {});});++describe("extractReadablePage", () => {+ afterEach(() => {+ Reflect.deleteProperty(fakeBrowser, "scripting");+ });++ it("runs the readability script in the tab and returns its result", async () => {+ const page = { title: "Article", content: "<p>Body</p>" };+ const executeScript = vi.fn()+ .mockResolvedValueOnce([ { result: page } ])+ .mockResolvedValueOnce([ { result: null } ])+ .mockResolvedValueOnce([]);+ Object.assign(fakeBrowser, { scripting: { executeScript } });++ expect(await extractReadablePage(7)).toBe(page);+ expect(executeScript).toHaveBeenCalledWith({ target: { tabId: 7 }, files: [ "/readability.js" ] });+ expect(await extractReadablePage(7)).toBeUndefined();+ expect(await extractReadablePage(7)).toBeUndefined();+ });+});+function setUrl(url: string) {(window as unknown as HappyDOMWindow).happyDOM.setURL(url);}diff --git a/apps/web-clipper/utils.ts b/apps/web-clipper/utils.tsindex 74fab6c705..7297d4327a 100644--- a/apps/web-clipper/utils.ts+++ b/apps/web-clipper/utils.ts@@ -1,5 +1,31 @@export type Rect = { x: number, y: number, width: number, height: number };+/** An image of a clipping; the clipping's `content` references it by `imageId`. */+export type ClippedImage = { imageId: string, src: string };++/** The readable version of a page, as `entrypoints/readability/index.ts` extracts it. */+export interface ReadablePage {+ title: string;+ content: string;+ images: ClippedImage[];+ pageUrl: string;+ clipType: "page";+ labels: Record<string, string>;+}++/**+ * Runs `entrypoints/readability/index.ts` in the tab and returns the page it read, or `undefined`+ * when the page has no article. Throws where the extension cannot run scripts, such as browser+ * pages.+ */+export async function extractReadablePage(tabId: number): Promise<ReadablePage | undefined> {+ const [ injection ] = await browser.scripting.executeScript({+ target: { tabId },+ files: [ "/readability.js" ]+ });+ return (injection?.result ?? undefined) as ReadablePage | undefined;+}+export function randomString(len: number) {let text = "";const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";@@ -28,3 +54,63 @@ export function createLink(clickAction: object, text: string, color = "lightskybreturn link;}++/** The page's own summary, preferred to the one it gives social sites, on a single line. */+export 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;+}++/** The `#pageDescription` label of every clip of the page, if the page has one. */+export function descriptionLabels(): Record<string, string> {+ const description = getPageDescription();+ return description ? { pageDescription: description } : {};+}++export function makeLinksAbsolute(container: HTMLElement) {+ // `link.href` reads the URL the browser resolved against the page, and leaves+ // `mailto:`, `tel:` and other non-web schemes unchanged.+ for (const link of container.getElementsByTagName('a')) {+ if (link.href) {+ link.setAttribute("href", link.href);+ }+ }+}++/** Replaces the `src` of each image in `container` with an `imageId`, the same one for the same image. */+export function getImages(container: HTMLElement) {+ const images: ClippedImage[] = [];++ for (const img of container.getElementsByTagName('img')) {+ if (!img.src) {+ continue;+ }++ const existingImage = images.find(image => image.src === img.src);++ if (existingImage) {+ img.src = existingImage.imageId;+ }+ else {+ const imageId = randomString(20);++ images.push({+ imageId,+ src: img.src+ });++ img.src = imageId;+ }+ }++ return images;+}diff --git a/apps/web-clipper/wxt.config.ts b/apps/web-clipper/wxt.config.tsindex 9830a86bce..eae4e0bc22 100644--- a/apps/web-clipper/wxt.config.ts+++ b/apps/web-clipper/wxt.config.ts@@ -22,6 +22,7 @@ export default defineConfig({"tabs","storage","contextMenus",+ "scripting",manifestVersion === 3 && "offscreen"].filter(Boolean),host_permissions: [