AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
feat(extension): save selected text from the context menu
tianma-if26ebc3304a89
diff --git a/apps/extension/README.md b/apps/extension/README.mdindex 99613233..c22ff04f 100644--- a/apps/extension/README.md+++ b/apps/extension/README.md@@ -9,6 +9,7 @@ Chrome, Edge, and Firefox Manifest V3 extension for saving the current webpage,- Click the extension action to capture the selected content, or extract the article body with Mozilla Readability when there is no selection.- Convert the extracted article HTML into Markdown with Turndown before uploading it.- Right-click an image and choose **Save image to EdgeEver**. The image file is uploaded into a new note in the default notebook, with the source page linked underneath.+- Select text on a page, right-click, and choose **Save selection to EdgeEver**. That passage is saved as a new note in the default notebook, with the source page linked underneath. The rest of the page is not included.- On X, right-click a post and choose **Save this post to EdgeEver**. The post text, author, time, and photos already shown in that post are saved into one note. Text folded behind Show more is expanded first, so a long post is saved in full. A single-post page can be saved immediately. On a timeline, the extension asks once for access to X so it can remember the post under the pointer.- When the page cannot hand over the image bytes, the extension asks once for access to that image's site. After that, later images from the same site save directly.- Create a searchable EdgeEver memo with the source URL and a `web-clip` tag.diff --git a/apps/extension/options.html b/apps/extension/options.htmlindex ebb1a0c2..73ca5ff5 100644--- a/apps/extension/options.html+++ b/apps/extension/options.html@@ -9,6 +9,7 @@<main class="options-shell"><h1 data-i18n="extensionName">EdgeEver Web Clipper</h1><p class="hint" data-i18n="imageSaveHint">Right-click an image on a webpage and choose “Save image to EdgeEver”. It is saved into the default notebook selected below.</p>+ <p class="hint" data-i18n="selectionSaveHint">Select text on a page, right-click, and choose “Save selection to EdgeEver”. It is saved as a new note in the default notebook selected below.</p><p class="hint" data-i18n="tweetSaveHint">On X, right-click a post and choose “Save this post to EdgeEver”. The visible text and photos go into one new note in the same notebook.</p><form id="settings-form"><label>diff --git a/apps/extension/package.json b/apps/extension/package.jsonindex 865cbf7f..0eabec5a 100644--- a/apps/extension/package.json+++ b/apps/extension/package.json@@ -9,7 +9,7 @@"dev": "vite --config vite.config.ts","lint:firefox": "web-ext lint --source-dir dist-firefox --output text","package:firefox": "bun run build:firefox && bun run lint:firefox && web-ext build --source-dir dist-firefox --artifacts-dir web-ext-artifacts --overwrite-dest",- "test": "bun test manifest.test.mjs image-clip.test.mjs tweet-clip.test.mjs"+ "test": "bun test manifest.test.mjs image-clip.test.mjs tweet-clip.test.mjs selection-clip.test.mjs"},"dependencies": {"@mozilla/readability": "^0.6.0",diff --git a/apps/extension/popup.html b/apps/extension/popup.htmlindex 986afd72..dd80d0f6 100644--- a/apps/extension/popup.html+++ b/apps/extension/popup.html@@ -14,7 +14,7 @@<p class="hint" data-i18n="webClipper">Web Clipper</p></div></header>- <p class="popup-description" data-i18n="popupDescription">Clip the current page or selection. Right-click an image to save it, or right-click a post on X to save that post.</p>+ <p class="popup-description" data-i18n="popupDescription">Clip the current page or selection. Right-click selected text to save that passage, right-click an image to save it, or right-click a post on X to save that post.</p><button id="save" class="save-button" type="button"><svg aria-hidden="true" viewBox="0 0 24 24" width="18" height="18"><path d="M5 4.75A1.75 1.75 0 0 1 6.75 3h8.836c.464 0 .91.184 1.238.513l1.663 1.663c.329.328.513.774.513 1.238v12.836A1.75 1.75 0 0 1 17.25 21H6.75A1.75 1.75 0 0 1 5 19.25V4.75Z" />diff --git a/apps/extension/public/_locales/en/messages.json b/apps/extension/public/_locales/en/messages.jsonindex 22f690ed..fc680496 100644--- a/apps/extension/public/_locales/en/messages.json+++ b/apps/extension/public/_locales/en/messages.json@@ -12,7 +12,7 @@"message": "Web Clipper"},"popupDescription": {- "message": "Clip the current page or selection. Right-click an image to save it, or right-click a post on X to save that post."+ "message": "Clip the current page or selection. Right-click selected text to save that passage, right-click an image to save it, or right-click a post on X to save that post."},"saveCurrentPage": {"message": "Clip current page"@@ -196,6 +196,24 @@"emptyPageContent": {"message": "(No readable content was found on this page)"},+ "saveSelectionToEdgeEver": {+ "message": "Save selection to EdgeEver"+ },+ "selectionSaveHint": {+ "message": "Select text on a page, right-click, and choose “Save selection to EdgeEver”. It is saved as a new note in the default notebook selected below."+ },+ "savingSelection": {+ "message": "Saving the selection…"+ },+ "selectionSaved": {+ "message": "Saved the selection as a note."+ },+ "selectionEmpty": {+ "message": "No text was selected, so nothing was saved."+ },+ "selectionNoteFallbackTitle": {+ "message": "Selection"+ },"saveImageToEdgeEver": {"message": "Save image to EdgeEver"},diff --git a/apps/extension/public/_locales/ja/messages.json b/apps/extension/public/_locales/ja/messages.jsonindex f19aa595..c5ea2975 100644--- a/apps/extension/public/_locales/ja/messages.json+++ b/apps/extension/public/_locales/ja/messages.json@@ -12,7 +12,7 @@"message": "Web Clipper"},"popupDescription": {- "message": "表示中のページや選択した内容を取り込みます。画像の右クリックで画像を、X 上の投稿の右クリックでその投稿を保存できます。"+ "message": "表示中のページや選択した内容を取り込みます。選択した文字の右クリックでその文章を、画像の右クリックで画像を、X 上の投稿の右クリックでその投稿を保存できます。"},"saveCurrentPage": {"message": "このページを取り込む"@@ -196,6 +196,24 @@"emptyPageContent": {"message": "(このページから読み取れる本文はありませんでした)"},+ "saveSelectionToEdgeEver": {+ "message": "選択した文字を EdgeEver に保存"+ },+ "selectionSaveHint": {+ "message": "ページ上の文字を選択して右クリックし、「選択した文字を EdgeEver に保存」を選びます。その文章は、上で選んだ既定のノートブックに 1 件のノートとして保存されます。"+ },+ "savingSelection": {+ "message": "選択した文字を保存しています…"+ },+ "selectionSaved": {+ "message": "選択した文字をノートとして保存しました。"+ },+ "selectionEmpty": {+ "message": "選択された文字がないため、保存しませんでした。"+ },+ "selectionNoteFallbackTitle": {+ "message": "選択した文字"+ },"saveImageToEdgeEver": {"message": "画像を EdgeEver に保存"},diff --git a/apps/extension/public/_locales/zh_CN/messages.json b/apps/extension/public/_locales/zh_CN/messages.jsonindex 1ebef711..55abeb52 100644--- a/apps/extension/public/_locales/zh_CN/messages.json+++ b/apps/extension/public/_locales/zh_CN/messages.json@@ -12,7 +12,7 @@"message": "网页剪藏"},"popupDescription": {- "message": "剪藏当前网页或选中内容。在图片上右键可以保存图片;在 X 上右键可以保存这条推文。"+ "message": "剪藏当前网页或选中内容。选中文字后右键可以保存这段文字;在图片上右键可以保存图片;在 X 上右键可以保存这条推文。"},"saveCurrentPage": {"message": "剪藏当前网页"@@ -196,6 +196,24 @@"emptyPageContent": {"message": "(网页没有可提取的正文内容)"},+ "saveSelectionToEdgeEver": {+ "message": "保存选中文字到 EdgeEver"+ },+ "selectionSaveHint": {+ "message": "选中网页上的一段文字后右键,选择“保存选中文字到 EdgeEver”。这段文字会存成一条新笔记,放进上面选择的默认笔记本。"+ },+ "savingSelection": {+ "message": "正在保存选中文字……"+ },+ "selectionSaved": {+ "message": "已把选中文字存成一条笔记。"+ },+ "selectionEmpty": {+ "message": "没有选中文字,没有保存。"+ },+ "selectionNoteFallbackTitle": {+ "message": "选中文字"+ },"saveImageToEdgeEver": {"message": "保存图片到 EdgeEver"},diff --git a/apps/extension/selection-clip.test.mjs b/apps/extension/selection-clip.test.mjsnew file mode 100644index 00000000..f6d1aacc--- /dev/null+++ b/apps/extension/selection-clip.test.mjs@@ -0,0 +1,25 @@+import { describe, expect, test } from "bun:test";+import { selectionNoteMarkdown, selectionNoteTitle } from "./src/selection-clip.ts";++describe("selection note", () => {+ test("uses the selected passage as the title and keeps the page as a fallback", () => {+ expect(selectionNoteTitle("第一句。\n后面还有", "文章标题", "选中文字")).toBe("第一句。 后面还有");+ expect(selectionNoteTitle(" ", "文章标题", "选中文字")).toBe("文章标题");+ expect(selectionNoteTitle("", "", "选中文字")).toBe("选中文字");+ expect(selectionNoteTitle("字".repeat(100), "", "选中文字")).toHaveLength(80);+ });++ test("saves the passage and a source link without the rest of the page", () => {+ const markdown = selectionNoteMarkdown({+ markdown: "保留的段落。\n\n\n\n第二段。",+ pageUrl: "https://example.com/a(b)",+ capturedAt: "2026-09-27T00:00:00.000Z",+ sourceLabel: "来源",+ capturedAtLabel: "抓取时间",+ });+ expect(markdown.startsWith("保留的段落。\n\n第二段。")).toBe(true);+ expect(markdown).toContain("[https://example.com/a(b)](https://example.com/a%28b%29)");+ expect(markdown).toContain("抓取时间: 2026-09-27T00:00:00.000Z");+ expect(markdown).not.toContain("\n\n\n");+ });+});diff --git a/apps/extension/src/background.ts b/apps/extension/src/background.tsindex 6ba8e896..3a6457b7 100644--- a/apps/extension/src/background.ts+++ b/apps/extension/src/background.ts@@ -22,6 +22,10 @@ import {type StoredImage,type StoredImageFailure,} from "./image-clip";+import {+ selectionNoteMarkdown,+ selectionNoteTitle,+} from "./selection-clip";import {canonicalStatusUrl,isCapturedTweet,@@ -35,6 +39,8 @@ type CapturedPage = {title: string;url: string;markdown: string;+ plainText?: string;+ kind?: "page" | "selection";};type PendingImageSave = {@@ -49,6 +55,7 @@ type PendingImageSave = {};const IMAGE_MENU_ID = "save-image";+const SELECTION_MENU_ID = "save-selection";const TWEET_MENU_ID = "save-tweet";const PENDING_IMAGE_SAVE_KEY = "pendingImageSave";const IMAGE_SAVE_WINDOW_KEY = "imageSaveWindowId";@@ -94,17 +101,18 @@ const describeSaveError = (error: unknown) => {return t("saveFailedWithReason", message || t("saveFailed"));};-const createMemo = async (settings: ExtensionSettings, page: CapturedPage) => {+const notebookForClip = async (settings: ExtensionSettings) => {const notebooks = await listNotebooks(settings);const notebookId = settings.notebookId || notebooks.notebooks[0]?.id;- if (!notebookId) {- throw new Error(t("noAvailableNotebooks"));- }+ if (!notebookId) throw new Error(t("noAvailableNotebooks"));+ return notebookId;+};+const createMemo = async (settings: ExtensionSettings, page: CapturedPage) => {await edgeEverRequest(settings, "/api/v1/memos", {method: "POST",body: JSON.stringify({- notebookId,+ notebookId: await notebookForClip(settings),title: page.title,contentMarkdown: toMarkdown(page),tags: ["web-clip"],@@ -579,7 +587,122 @@ const saveTweetFromMenu = async (}};+const isCapturedPage = (value: unknown): value is CapturedPage => {+ if (!value || typeof value !== "object") return false;+ const record = value as Partial<CapturedPage>;+ return typeof record.title === "string"+ && typeof record.url === "string"+ && typeof record.markdown === "string";+};++const readCapturedPage = async (tabId: number, frameId: number | null, mode: "page" | "selection") => {+ const result = await new Promise<unknown>((resolve, reject) => {+ const timeout = setTimeout(() => {+ pendingCapture = null;+ reject(new Error(t("captureTimeout")));+ }, 15_000);+ pendingCapture = (page) => {+ clearTimeout(timeout);+ resolve(page);+ };+ const target = scriptTarget(tabId, frameId);+ const inject = async () => {+ await chrome.scripting.executeScript({+ target,+ func: (value: unknown) => {+ (globalThis as { __edgeeverPageClipPayload?: unknown }).__edgeeverPageClipPayload = value;+ },+ args: [{ mode }],+ });+ await chrome.scripting.executeScript({+ target,+ files: ["assets/capture.js"],+ });+ };+ void inject().catch((error: unknown) => {+ clearTimeout(timeout);+ pendingCapture = null;+ reject(new Error(describeCaptureError(error)));+ });+ });+ if (!isCapturedPage(result)) throw new Error(t("captureScriptFailed", t("captureUnknownError")));+ return result;+};++const describeSelectionError = (error: unknown) => {+ const message = error instanceof Error ? error.message : "";+ if (+ message === t("completePluginConfiguration")+ || message === t("instancePermissionRequired")+ || message === t("noAvailableNotebooks")+ || message === t("selectionEmpty")+ || message === t("captureTimeout")+ || message === t("pageAccessDenied")+ ) {+ return message;+ }+ const captureScriptPrefix = t("captureScriptFailed", "\u0000").split("\u0000")[0] ?? "";+ if (captureScriptPrefix && message.startsWith(captureScriptPrefix)) return message;+ return describeSaveError(error);+};++const saveSelectionFromMenu = async (+ info: { pageUrl?: string; frameId?: number; selectionText?: string },+ tab?: { id?: number; url?: string; title?: string },+) => {+ const tabId = typeof tab?.id === "number" ? tab.id : null;+ const frameId = typeof info.frameId === "number" ? info.frameId : null;+ const pageUrl = tab?.url || info.pageUrl || "";+ const pageTitle = tab?.title || "";+ const browserSelection = (info.selectionText || "").replace(/\u00a0/g, " ").trim();+ try {+ const settings = await ensureClipperReady();+ if (!tabId) throw new Error(t("selectionEmpty"));+ await showFeedback(tabId, frameId, t("savingSelection"), "success");+ let captured: CapturedPage | null = null;+ try {+ captured = await readCapturedPage(tabId, frameId, "selection");+ } catch (error) {+ if (!browserSelection) throw error;+ }+ const fromSelection = captured?.kind === "selection" ? captured : null;+ const markdown = fromSelection?.markdown.trim() || browserSelection;+ const plain = fromSelection?.plainText?.trim() || browserSelection || markdown;+ if (!markdown.trim()) throw new Error(t("selectionEmpty"));+ await edgeEverRequest(settings, "/api/v1/memos", {+ method: "POST",+ body: JSON.stringify({+ notebookId: await notebookForClip(settings),+ title: selectionNoteTitle(plain, pageTitle, t("selectionNoteFallbackTitle")),+ contentMarkdown: selectionNoteMarkdown({+ markdown,+ pageUrl: fromSelection?.url || pageUrl,+ capturedAt: new Date().toISOString(),+ sourceLabel: t("sourceLabel"),+ capturedAtLabel: t("capturedAtLabel"),+ }),+ tags: ["web-clip"],+ }),+ });+ await showFeedback(tabId, frameId, t("selectionSaved"), "success");+ } catch (error) {+ const message = describeSelectionError(error);+ if (message === t("completePluginConfiguration") || message === t("instancePermissionRequired")) {+ await chrome.runtime.openOptionsPage();+ }+ await showFeedback(tabId, frameId, message, "error");+ }+};+const registerClipMenus = () => {+ chrome.contextMenus.create({+ id: SELECTION_MENU_ID,+ title: t("saveSelectionToEdgeEver"),+ contexts: ["selection"],+ documentUrlPatterns: ["http://*/*", "https://*/*"],+ }, () => {+ void chrome.runtime.lastError;+ });chrome.contextMenus.create({id: IMAGE_MENU_ID,title: t("saveImageToEdgeEver"),@@ -601,7 +724,11 @@ const registerClipMenus = () => {chrome.runtime.onInstalled.addListener(registerClipMenus);registerClipMenus();-chrome.contextMenus.onClicked.addListener((info: { menuItemId?: string | number; srcUrl?: string; pageUrl?: string; frameId?: number }, tab?: { id?: number; url?: string; title?: string }) => {+chrome.contextMenus.onClicked.addListener((info: { menuItemId?: string | number; srcUrl?: string; pageUrl?: string; frameId?: number; selectionText?: string }, tab?: { id?: number; url?: string; title?: string }) => {+ if (info.menuItemId === SELECTION_MENU_ID) {+ void enqueueClip(() => saveSelectionFromMenu(info, tab));+ return;+ }if (info.menuItemId === IMAGE_MENU_ID) {void enqueueClip(() => saveImageFromMenu(info, tab));return;@@ -716,26 +843,7 @@ chrome.runtime.onMessage.addListener((message: { type?: string; page?: CapturedPthrow new Error(t("currentPageNotFound"));}- const page = await new Promise<CapturedPage>((resolve, reject) => {- const timeout = setTimeout(() => {- pendingCapture = null;- reject(new Error(t("captureTimeout")));- }, 15_000);-- pendingCapture = (capturedPage) => {- clearTimeout(timeout);- resolve(capturedPage);- };-- void chrome.scripting.executeScript({- target: { tabId: tab.id },- files: ["assets/capture.js"],- }).catch((error: unknown) => {- clearTimeout(timeout);- pendingCapture = null;- reject(new Error(describeCaptureError(error)));- });- });+ const page = await readCapturedPage(tab.id, null, "page");await createMemo(settings, page);sendResponse({ ok: true });} catch (error) {diff --git a/apps/extension/src/capture.ts b/apps/extension/src/capture.tsindex d4c71926..ae2cc211 100644--- a/apps/extension/src/capture.ts+++ b/apps/extension/src/capture.ts@@ -6,10 +6,19 @@ import TurndownService from "turndown";// modules and cannot resolve imports from the extension bundle.const t = (key: string) => chrome.i18n.getMessage(key) || key;+const root = globalThis as typeof globalThis & {+ __edgeeverPageClipPayload?: { mode?: string };+};+const clipPayload = root.__edgeeverPageClipPayload;+delete root.__edgeeverPageClipPayload;+const selectionOnly = clipPayload?.mode === "selection";+type CapturedPage = {title: string;url: string;markdown: string;+ plainText?: string;+ kind?: "page" | "selection";};const getSelectionHtml = () => {@@ -28,6 +37,29 @@ const getSelectionHtml = () => {const normalizeMarkdown = (value: string) => value.replace(/\n{3,}/g, "\n\n").trim();+const markdownFromHtml = (html: string) => {+ if (!html) return "";+ const turndown = new TurndownService({+ bulletListMarker: "-",+ codeBlockStyle: "fenced",+ headingStyle: "atx",+ linkStyle: "inlined",+ });+ return normalizeMarkdown(turndown.turndown(html));+};++const captureSelection = (): CapturedPage => {+ const plain = window.getSelection()?.toString().replace(/\u00a0/g, " ").trim() ?? "";+ const html = getSelectionHtml();+ return {+ title: document.title.trim() || location.hostname,+ url: location.href,+ markdown: markdownFromHtml(html) || plain,+ plainText: plain,+ kind: "selection",+ };+};+// Dynamic sites can contain very large inline SVGs, scripts, and embedded// documents. They are not article content, but cloning and parsing them makes// Readability disproportionately expensive (知乎 pages are a common example).@@ -65,36 +97,35 @@ const capturePage = (): CapturedPage => {}const title = article?.title?.trim() || document.title.trim() || location.hostname;- let markdown = "";- if (sourceHtml) {- const turndown = new TurndownService({- bulletListMarker: "-",- codeBlockStyle: "fenced",- headingStyle: "atx",- linkStyle: "inlined",- });- markdown = normalizeMarkdown(turndown.turndown(sourceHtml));- }-return {title,url: location.href,- markdown: markdown || textFallback(),+ markdown: markdownFromHtml(sourceHtml) || textFallback(),+ kind: "page",};};+const sendCapturedPage = (page: CapturedPage) => {+ void chrome.runtime.sendMessage({ type: "capturedPage", page });+};+try {- void chrome.runtime.sendMessage({ type: "capturedPage", page: capturePage() });+ sendCapturedPage(selectionOnly ? captureSelection() : capturePage());} catch {// Keep the injected script from failing silently if a page exposes an// unusual DOM implementation. The background page will show its timeout// message, while ordinary pages still use the normal extraction path.- void chrome.runtime.sendMessage({- type: "capturedPage",- page: {- title: document.title.trim() || location.hostname,- url: location.href,- markdown: textFallback(),- },+ // A selection save must not fall back to the whole page.+ sendCapturedPage(selectionOnly ? {+ title: document.title.trim() || location.hostname,+ url: location.href,+ markdown: "",+ plainText: "",+ kind: "selection",+ } : {+ title: document.title.trim() || location.hostname,+ url: location.href,+ markdown: textFallback(),+ kind: "page",});}diff --git a/apps/extension/src/selection-clip.ts b/apps/extension/src/selection-clip.tsnew file mode 100644index 00000000..a847b8a8--- /dev/null+++ b/apps/extension/src/selection-clip.ts@@ -0,0 +1,26 @@+const escapeMarkdownLabel = (value: string) =>+ value.replace(/[\r\n]+/g, " ").replace(/\\/g, "\\\\").replace(/\[/g, "\\[").replace(/\]/g, "\\]");++const markdownDestination = (value: string) =>+ value.replace(/\\/g, "%5C").replace(/ /g, "%20").replace(/\(/g, "%28").replace(/\)/g, "%29");++export const selectionNoteTitle = (text: string, pageTitle: string, fallback: string) => {+ const excerpt = text.replace(/\s+/g, " ").trim();+ const page = pageTitle.replace(/\s+/g, " ").trim();+ return (excerpt || page || fallback).slice(0, 80);+};++export const selectionNoteMarkdown = (input: {+ markdown: string;+ pageUrl: string;+ capturedAt: string;+ sourceLabel: string;+ capturedAtLabel: string;+}) => {+ const body = input.markdown.replace(/\r\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();+ const footer = [+ `${input.sourceLabel}: [${escapeMarkdownLabel(input.pageUrl)}](${markdownDestination(input.pageUrl)})`,+ `${input.capturedAtLabel}: ${input.capturedAt}`,+ ].join("\n\n");+ return body ? `${body}\n\n${footer}` : footer;+};