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 a right-clicked Zhihu answer or article as a note
tianma-ifb37a72ac9969
diff --git a/apps/extension/FIREFOX_STORE_LISTING.md b/apps/extension/FIREFOX_STORE_LISTING.mdindex b996e31b..a0621a0c 100644--- a/apps/extension/FIREFOX_STORE_LISTING.md+++ b/apps/extension/FIREFOX_STORE_LISTING.md@@ -3,7 +3,7 @@## Listing- Name: EdgeEver Web Clipper-- Summary: Save a webpage, selected text, an image, an X post, a Xiaohongshu note, or a GitHub repository to your EdgeEver instance.+- Summary: Save a webpage, selected text, an image, an X post, a Xiaohongshu note, a Zhihu answer or article, or a GitHub repository to your EdgeEver instance.- Category: Bookmarks- Homepage: https://edgeever.org- Support: https://github.com/tianma-if/edgeever/issues@@ -11,12 +11,13 @@## Description-EdgeEver Web Clipper saves the current webpage, selected text, a right-clicked image, an X post, a Xiaohongshu note, or a GitHub repository's address and description directly to the self-hosted EdgeEver instance you configure.+EdgeEver Web Clipper saves the current webpage, selected text, a right-clicked image, an X post, a Xiaohongshu note, a Zhihu answer or article, or a GitHub repository's address and description directly to the self-hosted EdgeEver instance you configure.- Extract readable article content, or right-click selected text and save that passage only.- Right-click an image and save that image file as a new note. From Google Search, the note records Google Search and the keyword.- On X, right-click the post text and save the full post, including text behind Show more, plus photos already shown.- On Xiaohongshu, right-click the note text and save the title, text, and photos. Comments are left out.+- On Zhihu, right-click the answer or article text and save the title, author, text, and photos. Comments are left out. On a feed or question page, the item under the pointer is saved.- On a GitHub repository page or code tree, right-click the page background, the description, or the README text and save the repository address and description.- These commands stay on the top-level right-click menu.- Convert captured HTML to Markdown locally.@@ -24,7 +25,7 @@ EdgeEver Web Clipper saves the current webpage, selected text, a right-clicked i- Send content directly to your instance without an EdgeEver-operated relay.- No advertising, analytics, tracking, or telemetry.-Before using the extension, enter your EdgeEver instance URL and API token in the extension settings. The extension reads and sends page content only after you click **Clip current page**, **Save selection to EdgeEver**, **Save image to EdgeEver**, **Save this post to EdgeEver**, **Save this Xiaohongshu note to EdgeEver**, or **Save this repository to EdgeEver**.+Before using the extension, enter your EdgeEver instance URL and API token in the extension settings. The extension reads and sends page content only after you click **Clip current page**, **Save selection to EdgeEver**, **Save image to EdgeEver**, **Save this post to EdgeEver**, **Save this Xiaohongshu note to EdgeEver**, **Save this Zhihu answer or article to EdgeEver**, or **Save this repository to EdgeEver**.## Data collection and transmission@@ -46,7 +47,8 @@ The project maintainers do not receive or retain this data. Instance settings ar8. Open one X post page, right-click the post text (not a photo), choose **Save this post to EdgeEver**, and verify the note contains the post text and the post link.9. Open one GitHub repository page, right-click the description or README text, choose **Save this repository to EdgeEver**, and verify the note contains the repository address and description.10. Open one Xiaohongshu note, right-click the note text (not a photo), choose **Save this Xiaohongshu note to EdgeEver**, and verify the note contains the title, text, and source link.-11. Verify the created notes in the review EdgeEver instance.+11. Open one Zhihu answer or article, right-click the text (not a photo), choose **Save this Zhihu answer or article to EdgeEver**, and verify the note contains the title, text, and source link.+12. Verify the created notes in the review EdgeEver instance.Restricted browser pages, extension stores, built-in PDF viewers, and other privileged pages cannot be captured.@@ -70,16 +72,17 @@ The reviewable source is the repository source before Vite bundling. Third-party## 中文商店说明-EdgeEver 网页剪藏插件可将当前网页、选中的文字、右键选中的图片、X 上的一条推文,或小红书上的一篇笔记直接保存到用户配置的自托管 EdgeEver 实例。+EdgeEver 网页剪藏插件可将当前网页、选中的文字、右键选中的图片、X 上的一条推文、小红书上的一篇笔记,或知乎上的一篇回答或文章直接保存到用户配置的自托管 EdgeEver 实例。- 提取适合阅读的文章正文。选中文字后右键,只保存这一段。- 在图片上右键,把图片文件存成一条新笔记。从 Google 搜索保存时,笔记记录“Google 搜索”和关键词。- 在 X 上右键推文正文。长文会先展开“显示更多”,再保存全文和已经显示的图片。- 在小红书笔记正文上右键,保存标题、正文和图片。评论不会写入。+- 在知乎回答或文章正文上右键,保存标题、作者、正文和图片。评论不会写入。首页和问题页保存的是指针下的那一篇。- 这些命令直接出现在右键菜单的第一级。- 在浏览器本地将 HTML 转换为 Markdown。- 可选择默认 EdgeEver 笔记本。- 数据直接发送到用户自己的实例,不经过 EdgeEver 中转服务。- 不包含广告、分析、追踪或遥测。-使用前,请在插件设置中填写 EdgeEver 实例地址和 API Token。插件只会在用户点击“剪藏当前网页”,或选择“保存选中文字到 EdgeEver”“保存图片到 EdgeEver”“保存这条推文到 EdgeEver”“保存这篇小红书笔记到 EdgeEver”后读取并发送网页内容。+使用前,请在插件设置中填写 EdgeEver 实例地址和 API Token。插件只会在用户点击“剪藏当前网页”,或选择“保存选中文字到 EdgeEver”“保存图片到 EdgeEver”“保存这条推文到 EdgeEver”“保存这篇小红书笔记到 EdgeEver”“保存这篇知乎回答或文章到 EdgeEver”后读取并发送网页内容。diff --git a/apps/extension/README.md b/apps/extension/README.mdindex 229611ab..3738905f 100644--- a/apps/extension/README.md+++ b/apps/extension/README.md@@ -12,6 +12,7 @@ Chrome, Edge, and Firefox Manifest V3 extension for saving the current webpage,- 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 the post text 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. Right-clicking a photo saves that image instead, so the command stays on the top-level menu. 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.- On Xiaohongshu, right-click the note text and choose **Save this Xiaohongshu note to EdgeEver**. The title, text, author, time, location, and photos go into one note. Comments are left out. Right-clicking a photo saves that image instead. An open note can be saved immediately. On the feed, the extension asks once for access to Xiaohongshu so it can remember the note under the pointer; open that note before saving if its full text is not on the page.+- On Zhihu, right-click the answer or article text and choose **Save this Zhihu answer or article to EdgeEver**. The title, author, full text, and photos go into one note. Comments are left out. Right-clicking a photo saves that image instead. An open answer or article can be saved immediately. On the home feed or a question page, the extension remembers the item under the pointer; if that listener is not running yet, right-click the same text once more.- On a GitHub repository page or code tree, right-click the page background, the description, or the README text and choose **Save this repository to EdgeEver**. The note keeps the repository address, the About text, and the homepage, language, license, and topics when the page shows them. An empty About falls back to the README's first paragraph. Issue, discussion, and single-file pages are left unsaved. The toolbar action uses the same card on those repository pages. Right-clicking a link or an image keeps the existing selection and image commands, so this one stays on the top-level menu.- 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/STORE_LISTING.md b/apps/extension/STORE_LISTING.mdindex c1c768f6..29517bf7 100644--- a/apps/extension/STORE_LISTING.md+++ b/apps/extension/STORE_LISTING.md@@ -27,11 +27,11 @@ Select the matching language in the Chrome Web Store developer dashboard and ent#### Summary-将当前网页、选中文字、右键图片、X 推文、小红书笔记或 GitHub 仓库保存到你自托管的 EdgeEver 实例。+将当前网页、选中文字、右键图片、X 推文、小红书笔记、知乎回答或文章,或 GitHub 仓库保存到你自托管的 EdgeEver 实例。#### Detailed description-EdgeEver Web Clipper 可以把当前网页、选中的文字、右键选中的图片、X 上的一条推文、小红书上的一篇笔记,或 GitHub 仓库的地址和简介保存到自托管的 EdgeEver 实例。+EdgeEver Web Clipper 可以把当前网页、选中的文字、右键选中的图片、X 上的一条推文、小红书上的一篇笔记、知乎上的一篇回答或文章,或 GitHub 仓库的地址和简介保存到自托管的 EdgeEver 实例。主要功能:@@ -40,13 +40,14 @@ EdgeEver Web Clipper 可以把当前网页、选中的文字、右键选中的- 在图片上右键,选择“保存图片到 EdgeEver”,把图片文件存成一条新笔记。- 在 X 上右键推文正文,选择“保存这条推文到 EdgeEver”。长文会先展开“显示更多”,再保存全文和已经显示的图片。- 在小红书笔记正文上右键,选择“保存这篇小红书笔记到 EdgeEver”。标题、正文和图片会存成一条笔记,评论不会写入。+- 在知乎回答或文章正文上右键,选择“保存这篇知乎回答或文章到 EdgeEver”。标题、作者、正文和图片会存成一条笔记,评论不会写入。首页和问题页保存的是指针下的那一篇。- 在 GitHub 仓库主页或代码目录上,右键页面空白、简介或 README 正文,选择“保存这个仓库到 EdgeEver”。笔记保留仓库地址和简介;页面上有主页、语言、许可证和话题时一并写入。- 这几项命令直接出现在右键菜单的第一级。- 在笔记中保留来源和剪藏时间。从 Google 搜索保存的图片记录“Google 搜索”和关键词。- 可选择默认笔记本,并自动添加 `web-clip` 标签。- 网页内容直接发送到你配置的 EdgeEver 实例,不经过开发者的中转服务器。-使用前,请在插件设置中填写 EdgeEver 实例地址和 API Token。插件只会在你点击“剪藏当前网页”,或选择“保存选中文字到 EdgeEver”“保存图片到 EdgeEver”“保存这条推文到 EdgeEver”“保存这篇小红书笔记到 EdgeEver”“保存这个仓库到 EdgeEver”后读取当前标签页。图片若无法由页面直接交出,才会再向你请求该图片所在网站的访问权限。+使用前,请在插件设置中填写 EdgeEver 实例地址和 API Token。插件只会在你点击“剪藏当前网页”,或选择“保存选中文字到 EdgeEver”“保存图片到 EdgeEver”“保存这条推文到 EdgeEver”“保存这篇小红书笔记到 EdgeEver”“保存这篇知乎回答或文章到 EdgeEver”“保存这个仓库到 EdgeEver”后读取当前标签页。图片若无法由页面直接交出,才会再向你请求该图片所在网站的访问权限。EdgeEver 是开源、自托管的现代笔记工作区。项目主页与源代码:https://github.com/tianma-if/edgeever@@ -54,11 +55,11 @@ EdgeEver 是开源、自托管的现代笔记工作区。项目主页与源代#### Summary-Save a webpage, selected text, a right-clicked image, an X post, a Xiaohongshu note, or a GitHub repository to your self-hosted EdgeEver.+Save a webpage, selected text, a right-clicked image, an X post, a Xiaohongshu note, a Zhihu answer or article, or a GitHub repository to your self-hosted EdgeEver.#### Detailed description-EdgeEver Web Clipper saves the current webpage, selected text, a right-clicked image, an X post, a Xiaohongshu note, or a GitHub repository's address and description to your self-hosted EdgeEver instance.+EdgeEver Web Clipper saves the current webpage, selected text, a right-clicked image, an X post, a Xiaohongshu note, a Zhihu answer or article, or a GitHub repository's address and description to your self-hosted EdgeEver instance.Key features:@@ -67,13 +68,14 @@ Key features:- Right-click an image and choose “Save image to EdgeEver” to store the image file as a new note.- On X, right-click the post text and choose “Save this post to EdgeEver”. Long posts are expanded before saving, so the full text and already shown photos go into one note.- On Xiaohongshu, right-click the note text and choose “Save this Xiaohongshu note to EdgeEver”. The title, text, and photos go into one note. Comments are left out.+- On Zhihu, right-click the answer or article text and choose “Save this Zhihu answer or article to EdgeEver”. The title, author, text, and photos go into one note. Comments are left out. On the home feed or a question page, the item under the pointer is saved.- On a GitHub repository page or code tree, right-click the page background, the description, or the README text and choose “Save this repository to EdgeEver”. The note keeps the address and description, plus the homepage, language, license, and topics when the page shows them.- These commands stay on the top-level right-click menu.- Preserve the source and clipping time in the note. An image saved from Google Search records “Google Search” and the keyword.- Select a default notebook and add the `web-clip` tag automatically.- Send webpage content directly to your configured EdgeEver instance without a developer-operated relay server.-Before using the extension, enter your EdgeEver instance URL and API token in the extension settings. The extension reads the current tab only after you click “Clip current page” or choose “Save selection to EdgeEver”, “Save image to EdgeEver”, “Save this post to EdgeEver”, “Save this Xiaohongshu note to EdgeEver”, or “Save this repository to EdgeEver”. It asks for access to an image's site only when that page cannot provide the image file.+Before using the extension, enter your EdgeEver instance URL and API token in the extension settings. The extension reads the current tab only after you click “Clip current page” or choose “Save selection to EdgeEver”, “Save image to EdgeEver”, “Save this post to EdgeEver”, “Save this Xiaohongshu note to EdgeEver”, “Save this Zhihu answer or article to EdgeEver”, or “Save this repository to EdgeEver”. It asks for access to an image's site only when that page cannot provide the image file.EdgeEver is an open-source, self-hosted modern notes workspace. Project homepage and source code: https://github.com/tianma-if/edgeever@@ -81,15 +83,15 @@ EdgeEver is an open-source, self-hosted modern notes workspace. Project homepage### Single purpose-Save the current webpage, user-selected text, a user-chosen image, one X post, one Xiaohongshu note, or one GitHub repository card to the self-hosted EdgeEver instance explicitly configured by the user.+Save the current webpage, user-selected text, a user-chosen image, one X post, one Xiaohongshu note, one Zhihu answer or article, or one GitHub repository card to the self-hosted EdgeEver instance explicitly configured by the user.### Permission justifications-- `activeTab`: Read the active page only after the user clicks the extension's save action or chooses Save selection to EdgeEver, Save image to EdgeEver, Save this post to EdgeEver, Save this Xiaohongshu note to EdgeEver, or Save this repository to EdgeEver.-- `contextMenus`: Add one top-level item for the thing the user right-clicked: selected text, an image, an X post, a Xiaohongshu note, or a GitHub repository page. It runs only after the user selects that item.+- `activeTab`: Read the active page only after the user clicks the extension's save action or chooses Save selection to EdgeEver, Save image to EdgeEver, Save this post to EdgeEver, Save this Xiaohongshu note to EdgeEver, Save this Zhihu answer or article to EdgeEver, or Save this repository to EdgeEver.+- `contextMenus`: Add one top-level item for the thing the user right-clicked: selected text, an image, an X post, a Xiaohongshu note, a Zhihu answer or article, or a GitHub repository page. It runs only after the user selects that item.- `scripting`: Inject the packaged capture script into the active page after the user initiates a capture.- `storage`: Store the user's EdgeEver instance URL, API token, and default notebook ID locally.-- Optional host permissions: Send API requests only to the EdgeEver instance origin the user approves. If a page cannot provide an image file, the extension can also ask for access to that image's site, or to all sites when the user explicitly chooses that option, and uses it only to download the image the user chose to save. Saving a post from an X timeline asks for access to X so the extension can remember which post was under the pointer. The script on X only records that target and runs after the user allows it. Saving a note from a Xiaohongshu feed asks for access to Xiaohongshu for the same reason. An open note page can be saved without that extra permission.+- Optional host permissions: Send API requests only to the EdgeEver instance origin the user approves. If a page cannot provide an image file, the extension can also ask for access to that image's site, or to all sites when the user explicitly chooses that option, and uses it only to download the image the user chose to save. Saving a post from an X timeline asks for access to X so the extension can remember which post was under the pointer. The script on X only records that target and runs after the user allows it. Saving a note from a Xiaohongshu feed asks for access to Xiaohongshu for the same reason. An open note page can be saved without that extra permission. On Zhihu, a content script remembers which answer or article was under the pointer. It does not send the page anywhere. The full text is read only after the user chooses Save this Zhihu answer or article to EdgeEver, and it is sent only to the user's EdgeEver instance. If that listener is missing, the extension asks once for access to Zhihu and then asks the user to right-click the same text again.### Data disclosuresdiff --git a/apps/extension/manifest.base.json b/apps/extension/manifest.base.jsonindex a2d503dd..06a68e61 100644--- a/apps/extension/manifest.base.json+++ b/apps/extension/manifest.base.json@@ -39,6 +39,16 @@],"js": ["assets/xhs-target.js"],"run_at": "document_start"+ },+ {+ "matches": [+ "https://www.zhihu.com/*",+ "https://zhihu.com/*",+ "https://zhuanlan.zhihu.com/*",+ "https://www.zhuanlan.zhihu.com/*"+ ],+ "js": ["assets/zhihu-target.js"],+ "run_at": "document_start"}]}diff --git a/apps/extension/manifest.test.mjs b/apps/extension/manifest.test.mjsindex cec5ebfc..e75a92ea 100644--- a/apps/extension/manifest.test.mjs+++ b/apps/extension/manifest.test.mjs@@ -39,6 +39,16 @@ describe("extension manifests", () => {js: ["assets/xhs-target.js"],run_at: "document_start",},+ {+ matches: [+ "https://www.zhihu.com/*",+ "https://zhihu.com/*",+ "https://zhuanlan.zhihu.com/*",+ "https://www.zhuanlan.zhihu.com/*",+ ],+ js: ["assets/zhihu-target.js"],+ run_at: "document_start",+ },]);}});diff --git a/apps/extension/options.html b/apps/extension/options.htmlindex 1a438253..88731275 100644--- a/apps/extension/options.html+++ b/apps/extension/options.html@@ -13,6 +13,7 @@<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><p class="hint" data-i18n="githubRepoSaveHint">On a GitHub repository page or code tree, right-click the page background, the description, or the README text and choose “Save this repository to EdgeEver”. The address and description are saved as a new note in the default notebook selected above.</p><p class="hint" data-i18n="xhsSaveHint">On Xiaohongshu, right-click the note text and choose “Save this Xiaohongshu note to EdgeEver”. The title, text, and photos go into one new note. Comments are left out.</p>+ <p class="hint" data-i18n="zhihuSaveHint">On Zhihu, right-click the answer or article text and choose “Save this Zhihu answer or article to EdgeEver”. The title, author, text, and photos go into one new note. Comments are left out.</p><form id="settings-form"><label><span data-i18n="instanceAddress">EdgeEver instance URL</span>diff --git a/apps/extension/package.json b/apps/extension/package.jsonindex 7001970f..c3689e4e 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 selection-clip.test.mjs github-repo.test.mjs xhs-clip.test.mjs"+ "test": "bun test manifest.test.mjs image-clip.test.mjs tweet-clip.test.mjs selection-clip.test.mjs github-repo.test.mjs xhs-clip.test.mjs zhihu-clip.test.mjs"},"dependencies": {"@mozilla/readability": "^0.6.0",diff --git a/apps/extension/public/_locales/en/messages.json b/apps/extension/public/_locales/en/messages.jsonindex 61ba16c8..df2f2351 100644--- a/apps/extension/public/_locales/en/messages.json+++ b/apps/extension/public/_locales/en/messages.json@@ -395,5 +395,47 @@},"xhsLocationLabel": {"message": "Location"+ },+ "saveZhihuToEdgeEver": {+ "message": "Save this Zhihu answer or article to EdgeEver"+ },+ "zhihuSaveHint": {+ "message": "On Zhihu, right-click the answer or article text and choose “Save this Zhihu answer or article to EdgeEver”. The title, author, text, and photos go into one new note. Comments are left out. Right-clicking a photo still saves that image only."+ },+ "savingZhihu": {+ "message": "Saving this Zhihu answer or article…"+ },+ "zhihuSaved": {+ "message": "Saved this Zhihu answer or article."+ },+ "zhihuNotFound": {+ "message": "Could not find that answer or article. Right-click its text."+ },+ "zhihuUnreadable": {+ "message": "Could not read that answer or article, so nothing was saved."+ },+ "zhihuPermissionIntro": {+ "message": "This page lists more than one answer or article. Allow access to Zhihu so the clipper can remember the one under the pointer. After that, right-click the same text once more. Only the item you choose is saved to the clipper's default notebook."+ },+ "zhihuPermissionToast": {+ "message": "Allow access to Zhihu to choose an answer or article in the list. Then right-click that text again."+ },+ "zhihuRightClickAgain": {+ "message": "Answers and articles on this page can be recognized now. Right-click that text again."+ },+ "allowZhihuAccess": {+ "message": "Allow access to Zhihu"+ },+ "zhihuPermissionDenied": {+ "message": "Access was not allowed. Right-click the text again to retry."+ },+ "zhihuPermissionReady": {+ "message": "Access allowed. Go back and right-click that text again."+ },+ "zhihuNoteFallbackTitle": {+ "message": "Zhihu answer or article"+ },+ "zhihuSaveWindowTitle": {+ "message": "Save this Zhihu answer or article to EdgeEver"}}diff --git a/apps/extension/public/_locales/ja/messages.json b/apps/extension/public/_locales/ja/messages.jsonindex e7ed5d94..654a5a88 100644--- a/apps/extension/public/_locales/ja/messages.json+++ b/apps/extension/public/_locales/ja/messages.json@@ -395,5 +395,47 @@},"xhsLocationLabel": {"message": "場所"+ },+ "saveZhihuToEdgeEver": {+ "message": "この知乎の回答または記事を EdgeEver に保存"+ },+ "zhihuSaveHint": {+ "message": "知乎で回答または記事の本文を右クリックし、「この知乎の回答または記事を EdgeEver に保存」を選びます。タイトル、著者、本文、画像が 1 件のノートになります。コメントは含めません。画像を右クリックした場合は、その画像だけを保存します。"+ },+ "savingZhihu": {+ "message": "この知乎の回答または記事を保存しています…"+ },+ "zhihuSaved": {+ "message": "この知乎の回答または記事を保存しました。"+ },+ "zhihuNotFound": {+ "message": "この回答または記事を特定できませんでした。本文を右クリックしてください。"+ },+ "zhihuUnreadable": {+ "message": "この回答または記事の本文を読めなかったため、保存しませんでした。"+ },+ "zhihuPermissionIntro": {+ "message": "ページには複数の回答や記事があります。ポインタの下にある一篇を覚えるには、知乎へのアクセスを許可してください。許可したあと、同じ本文をもう一度右クリックします。選んだ一篇だけを、クリップ拡張機能の既定ノートブックに保存します。"+ },+ "zhihuPermissionToast": {+ "message": "一覧で回答または記事を選ぶには、知乎へのアクセスを許可してください。そのあと、もう一度右クリックします。"+ },+ "zhihuRightClickAgain": {+ "message": "ページ上の回答と記事を識別できるようになりました。その本文をもう一度右クリックしてください。"+ },+ "allowZhihuAccess": {+ "message": "知乎へのアクセスを許可"+ },+ "zhihuPermissionDenied": {+ "message": "アクセスは許可されませんでした。本文をもう一度右クリックしてやり直してください。"+ },+ "zhihuPermissionReady": {+ "message": "許可しました。ページに戻り、その本文をもう一度右クリックしてください。"+ },+ "zhihuNoteFallbackTitle": {+ "message": "知乎の回答または記事"+ },+ "zhihuSaveWindowTitle": {+ "message": "この知乎の回答または記事を EdgeEver に保存"}}diff --git a/apps/extension/public/_locales/zh_CN/messages.json b/apps/extension/public/_locales/zh_CN/messages.jsonindex de8acb5e..64416768 100644--- a/apps/extension/public/_locales/zh_CN/messages.json+++ b/apps/extension/public/_locales/zh_CN/messages.json@@ -395,5 +395,47 @@},"xhsLocationLabel": {"message": "地点"+ },+ "saveZhihuToEdgeEver": {+ "message": "保存这篇知乎回答或文章到 EdgeEver"+ },+ "zhihuSaveHint": {+ "message": "在知乎回答或文章的正文上右键,选择“保存这篇知乎回答或文章到 EdgeEver”。标题、作者、正文和图片会存成一条新笔记,评论不会写入。右键图片仍然只保存这张图片。"+ },+ "savingZhihu": {+ "message": "正在保存这篇知乎内容……"+ },+ "zhihuSaved": {+ "message": "已把这篇知乎内容存成一条笔记。"+ },+ "zhihuNotFound": {+ "message": "没有定位到这篇回答或文章。请在正文上右键。"+ },+ "zhihuUnreadable": {+ "message": "没有读到这篇回答或文章的正文,没有保存。"+ },+ "zhihuPermissionIntro": {+ "message": "页面上有多篇回答或文章。允许访问知乎之后,插件才能记住指针下的这一篇。允许后,请再在同一篇正文上右键一次。只会把你选中的这一篇存进剪藏插件的默认笔记本。"+ },+ "zhihuPermissionToast": {+ "message": "需要允许访问知乎,才能在列表里选中这一篇。允许后请再右键一次。"+ },+ "zhihuRightClickAgain": {+ "message": "已经可以识别页面上的回答和文章。请再在正文上右键一次。"+ },+ "allowZhihuAccess": {+ "message": "允许访问知乎"+ },+ "zhihuPermissionDenied": {+ "message": "没有获得访问权限。请再在正文上右键一次来重新授权。"+ },+ "zhihuPermissionReady": {+ "message": "已允许。回到页面,再在这篇正文上右键一次。"+ },+ "zhihuNoteFallbackTitle": {+ "message": "一篇知乎内容"+ },+ "zhihuSaveWindowTitle": {+ "message": "保存这篇知乎回答或文章到 EdgeEver"}}diff --git a/apps/extension/src/background.ts b/apps/extension/src/background.tsindex 3f2e3a25..b1621cbc 100644--- a/apps/extension/src/background.ts+++ b/apps/extension/src/background.ts@@ -51,6 +51,18 @@ import {saveCapturedXhsNote,xhsNoteTitle,} from "./xhs-clip";+import {+ fetchZhihuItemInPage,+ isZhihuApiRead,+ isZhihuLocate,+ resolveZhihuNote,+ saveCapturedZhihuNote,+ zhihuBodyFromHtml,+ zhihuNoteTitle,+ zhihuTargetFromPageUrl,+ zhihuTimeIso,+ type ZhihuLocateSuccess,+} from "./zhihu-clip";import { t } from "./i18n";type CapturedPage = {@@ -98,6 +110,15 @@ const XHS_DOCUMENT_PATTERNS = ["https://www.xiaohongshu.com/*","https://xiaohongshu.com/*",];+const ZHIHU_MENU_ID = "save-zhihu";+const PENDING_ZHIHU_KEY = "pendingZhihuPermission";+const ZHIHU_WINDOW_KEY = "zhihuSaveWindowId";+const ZHIHU_DOCUMENT_PATTERNS = [+ "https://www.zhihu.com/*",+ "https://zhihu.com/*",+ "https://zhuanlan.zhihu.com/*",+ "https://www.zhuanlan.zhihu.com/*",+];const toMarkdown = (page: CapturedPage) => {const capturedAt = new Date().toISOString();@@ -412,11 +433,17 @@ const openXhsPermissionWindow = async (tabId: number | null) => {await focusExtensionWindow("xhs-save.html", XHS_WINDOW_KEY, 560);};+const openZhihuPermissionWindow = async (tabId: number | null) => {+ await chrome.storage.session.set({ [PENDING_ZHIHU_KEY]: { tabId } });+ await focusExtensionWindow("zhihu-save.html", ZHIHU_WINDOW_KEY, 560);+};+let pendingCapture: ((page: CapturedPage) => void) | null = null;const pendingImageReads = new Map<string, (result: unknown) => void>();const pendingTweetReads = new Map<string, (result: unknown) => void>();const pendingGithubReads = new Map<string, (result: unknown) => void>();const pendingXhsReads = new Map<string, (result: unknown) => void>();+const pendingZhihuReads = new Map<string, (result: unknown) => void>();let clipQueue = Promise.resolve();let completingImageSave = false;@@ -802,6 +829,149 @@ const saveXhsFromMenu = async (}};+const injectZhihuReader = async (tabId: number, frameId: number | null, payload: unknown) => {+ const target = scriptTarget(tabId, frameId);+ await chrome.scripting.executeScript({+ target,+ func: (value: unknown) => {+ (globalThis as { __edgeeverZhihuClipPayload?: unknown }).__edgeeverZhihuClipPayload = value;+ },+ args: [payload],+ });+ await chrome.scripting.executeScript({+ target,+ files: ["assets/capture-zhihu.js"],+ });+};++const injectZhihuTarget = async (tabId: number) => {+ await chrome.scripting.executeScript({+ target: { tabId },+ files: ["assets/zhihu-target.js"],+ });+};++const readZhihuLocate = async (tabId: number, frameId: number | null) => {+ const requestId = crypto.randomUUID();+ const result = await new Promise<unknown>((resolve, reject) => {+ const timeout = setTimeout(() => {+ pendingZhihuReads.delete(requestId);+ reject(new Error("timeout"));+ }, 10_000);+ pendingZhihuReads.set(requestId, (value) => {+ clearTimeout(timeout);+ resolve(value);+ });+ void injectZhihuReader(tabId, frameId, { requestId }).catch((error: unknown) => {+ clearTimeout(timeout);+ pendingZhihuReads.delete(requestId);+ reject(error);+ });+ });+ return isZhihuLocate(result) ? result : { ok: false as const, reason: "not-found" as const };+};++const readZhihuApi = async (tabId: number, frameId: number | null, located: ZhihuLocateSuccess) => {+ try {+ const [injected] = await chrome.scripting.executeScript({+ target: scriptTarget(tabId, frameId),+ world: "MAIN",+ func: fetchZhihuItemInPage,+ args: [{ kind: located.kind, id: located.id }],+ });+ return isZhihuApiRead(injected?.result) ? injected.result : null;+ } catch {+ return null;+ }+};++const describeZhihuError = (error: unknown) => {+ const message = error instanceof Error ? error.message : "";+ if (message === t("zhihuNotFound") || message === t("zhihuUnreadable")) return message;+ return describeImageError(error);+};++const saveLocatedZhihu = async (+ settings: ExtensionSettings,+ tabId: number,+ frameId: number | null,+ located: ZhihuLocateSuccess,+) => {+ const api = await readZhihuApi(tabId, frameId, located);+ const note = resolveZhihuNote(located, api);+ if (!note) throw new Error(t("zhihuUnreadable"));+ const body = zhihuBodyFromHtml(note.html, t("imageAltFallback"));+ if (!body.markdown && body.images.length === 0) throw new Error(t("zhihuUnreadable"));+ const images = [];+ for (const image of body.images) {+ const stored = await readTweetImage(tabId, frameId, image.url, image.alt || note.title || t("imageAltFallback"));+ if (stored) images.push({ ...stored, sourceUrl: image.url });+ }+ await saveCapturedZhihuNote(imageNoteClient(settings), {+ notebookId: settings.notebookId,+ title: zhihuNoteTitle({+ title: note.title,+ author: note.author,+ body: body.markdown,+ fallback: t("zhihuNoteFallbackTitle"),+ }),+ author: note.author,+ noteTitle: note.title,+ body: body.markdown,+ noteUrl: note.noteUrl,+ datetime: zhihuTimeIso(note.timeSeconds),+ images,+ capturedAt: new Date().toISOString(),+ sourceLabel: t("sourceLabel"),+ capturedAtLabel: t("capturedAtLabel"),+ timeLabel: t("tweetTimeLabel"),+ });+};++const saveZhihuFromMenu = async (+ info: { pageUrl?: string; frameId?: number },+ tab?: { id?: number; url?: string },+) => {+ const tabId = typeof tab?.id === "number" ? tab.id : null;+ const frameId = typeof info.frameId === "number" ? info.frameId : null;+ try {+ const settings = await ensureClipperReady();+ if (!tabId) throw new Error(t("zhihuNotFound"));+ let located: Awaited<ReturnType<typeof readZhihuLocate>>;+ try {+ located = await readZhihuLocate(tabId, frameId);+ } catch (error) {+ const raw = error instanceof Error ? error.message : String(error);+ if (/cannot access|missing host permission|permission/i.test(raw)) {+ await openZhihuPermissionWindow(tabId);+ await showFeedback(tabId, frameId, t("zhihuPermissionToast"), "success");+ return;+ }+ throw error;+ }+ if (!located.ok && located.reason === "needs-listener") {+ try {+ await injectZhihuTarget(tabId);+ await showFeedback(tabId, frameId, t("zhihuRightClickAgain"), "success");+ } catch {+ await openZhihuPermissionWindow(tabId);+ await showFeedback(tabId, frameId, t("zhihuPermissionToast"), "success");+ }+ return;+ }+ if (!located.ok) throw new Error(t("zhihuNotFound"));+ await showFeedback(tabId, frameId, t("savingZhihu"), "success");+ await saveLocatedZhihu(settings, tabId, frameId, located);+ await showFeedback(tabId, frameId, t("zhihuSaved"), "success");+ } catch (error) {+ const message = describeZhihuError(error);+ if (message === t("completePluginConfiguration") || message === t("instancePermissionRequired")) {+ await chrome.runtime.openOptionsPage();+ }+ await showFeedback(tabId, frameId, message, "error");+ }+};+const isGithubRepoSource = (value: unknown): value is GithubRepoPageSource => {if (!value || typeof value !== "object") return false;const record = value as Partial<GithubRepoPageSource>;@@ -1016,7 +1186,8 @@ const registerClipMenus = () => {// its items is visible. These contexts stay disjoint so each command remains// on the top-level menu: a photo saves the image, selected words save the// passage, the rest of an X post saves the post, a GitHub repository page- // saves the repository, and the rest of a Xiaohongshu note saves the note.+ // saves the repository, the rest of a Xiaohongshu note saves the note, and+ // the rest of a Zhihu answer or article saves that item.// Link context is omitted because a linked image would otherwise show both// commands. Recreate from scratch so a previous registration cannot keep an// overlapping item.@@ -1067,6 +1238,14 @@ const createClipMenus = () => {}, () => {void chrome.runtime.lastError;});+ chrome.contextMenus.create({+ id: ZHIHU_MENU_ID,+ title: t("saveZhihuToEdgeEver"),+ contexts: ["page", "video"],+ documentUrlPatterns: ZHIHU_DOCUMENT_PATTERNS,+ }, () => {+ void chrome.runtime.lastError;+ });};chrome.runtime.onInstalled.addListener(registerClipMenus);@@ -1091,11 +1270,15 @@ chrome.contextMenus.onClicked.addListener((info: { menuItemId?: string | number;}if (info.menuItemId === XHS_MENU_ID) {void enqueueClip(() => saveXhsFromMenu(info, tab));+ return;+ }+ if (info.menuItemId === ZHIHU_MENU_ID) {+ void enqueueClip(() => saveZhihuFromMenu(info, tab));}});chrome.windows.onRemoved.addListener((windowId: number) => {- void chrome.storage.session.get([IMAGE_SAVE_WINDOW_KEY, TWEET_WINDOW_KEY, XHS_WINDOW_KEY]).then((stored: Record<string, unknown>) => {+ void chrome.storage.session.get([IMAGE_SAVE_WINDOW_KEY, TWEET_WINDOW_KEY, XHS_WINDOW_KEY, ZHIHU_WINDOW_KEY]).then((stored: Record<string, unknown>) => {if (stored[IMAGE_SAVE_WINDOW_KEY] === windowId) {void chrome.storage.session.remove(IMAGE_SAVE_WINDOW_KEY);}@@ -1105,6 +1288,9 @@ chrome.windows.onRemoved.addListener((windowId: number) => {if (stored[XHS_WINDOW_KEY] === windowId) {void chrome.storage.session.remove(XHS_WINDOW_KEY);}+ if (stored[ZHIHU_WINDOW_KEY] === windowId) {+ void chrome.storage.session.remove(ZHIHU_WINDOW_KEY);+ }}).catch(() => undefined);});@@ -1139,6 +1325,12 @@ chrome.runtime.onMessage.addListener((message: { type?: string; page?: CapturedPreturn false;}+ if (message.type === "pageZhihuRead" && message.requestId) {+ pendingZhihuReads.get(message.requestId)?.(message.result);+ pendingZhihuReads.delete(message.requestId);+ return false;+ }+if (message.type === "activateTweetTarget") {void (async () => {const stored = await chrome.storage.session.get(PENDING_TWEET_KEY);@@ -1173,6 +1365,23 @@ chrome.runtime.onMessage.addListener((message: { type?: string; page?: CapturedPreturn true;}+ if (message.type === "activateZhihuTarget") {+ void (async () => {+ const stored = await chrome.storage.session.get(PENDING_ZHIHU_KEY);+ const pending = stored[PENDING_ZHIHU_KEY] as { tabId?: number | null } | undefined;+ if (typeof pending?.tabId === "number") {+ try {+ await injectZhihuTarget(pending.tabId);+ } catch {+ // The tab can be saved on the next right-click after it reloads.+ }+ }+ await chrome.storage.session.remove(PENDING_ZHIHU_KEY);+ sendResponse({ ok: true });+ })().catch(() => sendResponse({ ok: false }));+ return true;+ }+if (message.type === "getPendingImageSave") {void readPendingImageSave().then((pending) => {sendResponse(pending ? { originPattern: pending.originPattern, host: pending.host } : null);@@ -1246,6 +1455,14 @@ chrome.runtime.onMessage.addListener((message: { type?: string; page?: CapturedP}}+ if (zhihuTargetFromPageUrl(pageUrl)) {+ const located = await readZhihuLocate(tab.id, null);+ if (!located.ok) throw new Error(t("zhihuNotFound"));+ await saveLocatedZhihu(settings, tab.id, null, located);+ sendResponse({ ok: true });+ return;+ }+const page = await readCapturedPage(tab.id, null, "page");await createMemo(settings, page);sendResponse({ ok: true });@@ -1253,9 +1470,11 @@ chrome.runtime.onMessage.addListener((message: { type?: string; page?: CapturedPconst message = error instanceof Error ? error.message : "";sendResponse({ok: false,- message: message === t("captureTimeout") || message.startsWith(t("captureScriptFailed", ""))- ? describeCaptureError(error)- : describeSaveError(error),+ message: message === t("zhihuNotFound") || message === t("zhihuUnreadable")+ ? message+ : message === t("captureTimeout") || message.startsWith(t("captureScriptFailed", ""))+ ? describeCaptureError(error)+ : describeSaveError(error),});}})();diff --git a/apps/extension/src/capture-zhihu.ts b/apps/extension/src/capture-zhihu.tsnew file mode 100644index 00000000..e388b605--- /dev/null+++ b/apps/extension/src/capture-zhihu.ts@@ -0,0 +1,117 @@+// Injected on demand. Finds the answer or article marked by zhihu-target.js,+// or the one named by the page URL. Must stay import-free.+(() => {+ const root = globalThis as typeof globalThis & {+ __edgeeverZhihuTarget?: boolean;+ __edgeeverZhihuClipPayload?: { requestId?: string };+ };+ const payload = root.__edgeeverZhihuClipPayload;+ delete root.__edgeeverZhihuClipPayload;+ if (!payload || typeof payload.requestId !== "string") return;+ const requestId = payload.requestId;++ const finish = (result: Record<string, unknown>) => {+ void chrome.runtime.sendMessage({ type: "pageZhihuRead", requestId, result });+ };++ // Keep identical to targetFromLocation in zhihu-clip.ts.+ const targetFromLocation = (hostname: string, pathname: string) => {+ const host = hostname.toLowerCase();+ const articleHost = host === "zhuanlan.zhihu.com" || host === "www.zhuanlan.zhihu.com";+ if (articleHost) {+ const article = pathname.match(/^\/p\/(\d+)(?=\/|$)/);+ if (article?.[1]) return { kind: "article" as const, id: article[1], questionId: "" };+ return null;+ }+ const zhihuHost = host === "zhihu.com" || host === "www.zhihu.com";+ if (!zhihuHost) return null;+ const answer = pathname.match(/^\/question\/(\d+)\/answer\/(\d+)(?=\/|$)/);+ if (answer?.[1] && answer?.[2]) return { kind: "answer" as const, id: answer[2], questionId: answer[1] };+ const bare = pathname.match(/^\/answer\/(\d+)(?=\/|$)/);+ if (bare?.[1]) return { kind: "answer" as const, id: bare[1], questionId: "" };+ return null;+ };++ // Keep identical to questionIdFromHref in zhihu-clip.ts.+ const questionIdFromHref = (href: string) => {+ if (!href) return "";+ try {+ const url = new URL(href, "https://www.zhihu.com");+ return url.pathname.match(/^\/question\/(\d+)(?:\/answer\/\d+)?(?=\/|$)/)?.[1] ?? "";+ } catch {+ return "";+ }+ };++ const clean = (value: string) => value+ .replace(/\u200b/g, "")+ .replace(/\s+/g, " ")+ .trim();++ const textOf = (node: Element | null) => clean(node?.textContent || "");++ const readMarked = (node: Element) => {+ const kind = node.getAttribute("data-edgeever-zhihu-kind");+ const id = node.getAttribute("data-edgeever-zhihu-id") || "";+ if ((kind === "answer" || kind === "article") && /^\d+$/.test(id)) return { kind, id };+ return null;+ };++ const domSnapshot = (scope: Element | null, kind: "answer" | "article") => {+ const empty = { href: "", title: "", author: "", domHtml: "", domComplete: false };+ const root = scope || (kind === "article" ? document.querySelector(".Post-Main") : null);+ if (!root) return empty;+ const richCandidates = [...root.querySelectorAll(".RichText")]+ .filter((node) => !node.closest(".Comment, .Comments, .Comments-container, .HotComment, .ContentItem-actions"));+ const rich = kind === "article"+ ? (root.querySelector(".Post-RichText") || richCandidates[0] || null)+ : (richCandidates[0] || null);+ const collapsed = Boolean(+ root.querySelector(".RichContent.is-collapsed, button.ContentItem-more"),+ );+ const domHtml = (rich?.innerHTML || "").slice(0, 1_000_000);+ const href = root.querySelector(".ContentItem-title a")?.getAttribute("href") || "";+ const title = textOf(root.querySelector(".ContentItem-title, .Post-Title"))+ || (kind === "answer" ? textOf(document.querySelector(".QuestionHeader-title")) : "");+ const author = textOf(root.querySelector(".AuthorInfo-name"));+ return {+ href,+ title,+ author,+ domHtml,+ domComplete: Boolean(domHtml.trim()) && !collapsed,+ };+ };++ try {+ const marked = document.querySelector("[data-edgeever-zhihu-target='1']");+ const fromPage = targetFromLocation(location.hostname, location.pathname);+ const fromMark = marked ? readMarked(marked) : null;+ const chosen = fromMark || (!marked ? fromPage : null);+ if (!chosen) {+ finish({ ok: false, reason: root.__edgeeverZhihuTarget ? "not-found" : "needs-listener" });+ return;+ }+ const scope = marked+ || document.querySelector(`.ContentItem[name="${chosen.id}"]`);+ const kind = chosen.kind === "article" ? "article" : "answer";+ const dom = domSnapshot(scope, kind);+ const questionId = chosen.kind === "answer"+ ? (questionIdFromHref(dom.href) || (fromPage?.id === chosen.id ? fromPage.questionId : ""))+ : "";+ finish({+ ok: true,+ kind: chosen.kind,+ id: chosen.id,+ questionId,+ title: dom.title,+ author: dom.author,+ href: dom.href,+ pageUrl: location.href,+ domHtml: dom.domHtml,+ domComplete: dom.domComplete,+ });+ } catch {+ finish({ ok: false, reason: "not-found" });+ }+})();diff --git a/apps/extension/src/zhihu-clip.ts b/apps/extension/src/zhihu-clip.tsnew file mode 100644index 00000000..7fb5ba04--- /dev/null+++ b/apps/extension/src/zhihu-clip.ts@@ -0,0 +1,461 @@+import TurndownService from "turndown";+import type { ImageNoteClient } from "./image-clip";++const MAX_ZHIHU_IMAGES = 24;++export type ZhihuKind = "answer" | "article";++export type ZhihuTarget = {+ kind: ZhihuKind;+ id: string;+ questionId: string;+};++export type ZhihuLocateSuccess = {+ ok: true;+ kind: ZhihuKind;+ id: string;+ questionId: string;+ title: string;+ author: string;+ href: string;+ pageUrl: string;+ domHtml: string;+ domComplete: boolean;+};++export type ZhihuLocateFailure = {+ ok: false;+ reason: "not-found" | "needs-listener";+};++export type ZhihuLocate = ZhihuLocateSuccess | ZhihuLocateFailure;++export type ZhihuApiSuccess = {+ ok: true;+ kind: ZhihuKind;+ id: string;+ title: string;+ author: string;+ html: string;+ questionId: string;+ timeSeconds: number;+ truncated: boolean;+};++export type ZhihuApiFailure = {+ ok: false;+ reason: "unreadable";+};++export type ZhihuApiRead = ZhihuApiSuccess | ZhihuApiFailure;++export type ZhihuImageRef = {+ url: string;+ alt: string;+};++export type ResolvedZhihuNote = {+ kind: ZhihuKind;+ id: string;+ questionId: string;+ title: string;+ author: string;+ html: string;+ timeSeconds: number;+ noteUrl: string;+};++// Keep identical to targetFromLocation in capture-zhihu.ts and zhihu-target.ts.+const targetFromLocation = (hostname: string, pathname: string) => {+ const host = hostname.toLowerCase();+ const articleHost = host === "zhuanlan.zhihu.com" || host === "www.zhuanlan.zhihu.com";+ if (articleHost) {+ const article = pathname.match(/^\/p\/(\d+)(?=\/|$)/);+ if (article?.[1]) return { kind: "article" as const, id: article[1], questionId: "" };+ return null;+ }+ const zhihuHost = host === "zhihu.com" || host === "www.zhihu.com";+ if (!zhihuHost) return null;+ const answer = pathname.match(/^\/question\/(\d+)\/answer\/(\d+)(?=\/|$)/);+ if (answer?.[1] && answer?.[2]) return { kind: "answer" as const, id: answer[2], questionId: answer[1] };+ const bare = pathname.match(/^\/answer\/(\d+)(?=\/|$)/);+ if (bare?.[1]) return { kind: "answer" as const, id: bare[1], questionId: "" };+ return null;+};++const plainLine = (value: string) => value+ .replace(/\u200b/g, "")+ .replace(/[\r\n]+/g, " ")+ .replace(/\s+/g, " ")+ .trim();++const decodeBasicEntities = (value: string) => value+ .replace(/ /gi, " ")+ .replace(/&#(\d+);/g, (_match, digits: string) => {+ const code = Number(digits);+ return Number.isFinite(code) ? String.fromCodePoint(code) : "";+ })+ .replace(/&#x([0-9a-f]+);/gi, (_match, digits: string) => {+ const code = Number.parseInt(digits, 16);+ return Number.isFinite(code) ? String.fromCodePoint(code) : "";+ })+ .replace(/"/gi, "\"")+ .replace(/'|'/gi, "'")+ .replace(/</gi, "<")+ .replace(/>/gi, ">")+ .replace(/&/gi, "&");++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");++const escapeImageAlt = (value: string) =>+ plainLine(value).replace(/\\/g, "\\\\").replace(/\[/g, "\\[").replace(/\]/g, "\\]");++export const zhihuTargetFromPageUrl = (pageUrl: string): ZhihuTarget | null => {+ try {+ const url = new URL(pageUrl);+ return targetFromLocation(url.hostname, url.pathname);+ } catch {+ return null;+ }+};++export const questionIdFromHref = (href: string) => {+ if (!href) return "";+ try {+ const url = new URL(href, "https://www.zhihu.com");+ return url.pathname.match(/^\/question\/(\d+)(?:\/answer\/\d+)?(?=\/|$)/)?.[1] ?? "";+ } catch {+ return "";+ }+};++export const canonicalZhihuUrl = (target: ZhihuTarget) => {+ if (!/^\d+$/.test(target.id)) return "";+ if (target.kind === "article") return `https://zhuanlan.zhihu.com/p/${target.id}`;+ if (/^\d+$/.test(target.questionId)) {+ return `https://www.zhihu.com/question/${target.questionId}/answer/${target.id}`;+ }+ return `https://www.zhihu.com/answer/${target.id}`;+};++export const zhihuTimeIso = (seconds: number) => {+ if (!Number.isFinite(seconds) || seconds <= 0) return "";+ const ms = seconds < 1e11 ? seconds * 1000 : seconds;+ const date = new Date(ms);+ if (Number.isNaN(date.getTime())) return "";+ return date.toISOString();+};++export const normalizeZhihuImageUrl = (raw: string) => {+ const value = decodeBasicEntities(raw).trim();+ if (!value || value.startsWith("data:") || value.startsWith("blob:")) return "";+ try {+ const url = new URL(value);+ if (url.protocol !== "http:" && url.protocol !== "https:") return "";+ if (url.protocol === "http:") url.protocol = "https:";+ const host = url.hostname.toLowerCase();+ if (host.includes("avatar") || url.pathname.toLowerCase().includes("avatar")) return "";+ if (/\.(?:mp4|mov|m3u8|mp3)(?:$|\?)/i.test(`${url.pathname}${url.search}`)) return "";+ return url.toString();+ } catch {+ return "";+ }+};++const imageKey = (value: string) => {+ try {+ const url = new URL(value);+ const path = url.pathname.replace(/_(?:r|b|hd|qhd|\d+w)(?=\.[a-z0-9]+$)/i, "").toLowerCase();+ const host = url.hostname.toLowerCase();+ if (host === "zhimg.com" || host.endsWith(".zhimg.com")) return path;+ return `${host}${path}`;+ } catch {+ return value;+ }+};++const tagAttribute = (tag: string, name: string) => {+ const match = tag.match(new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'=<>]+))`, "i"));+ return decodeBasicEntities(match?.[1] || match?.[2] || match?.[3] || "");+};++const unwrapEntityLinks = (html: string) => html.replace(+ /<a\b[^>]*\bclass=(?:"[^"]*\bEntityWord\b[^"]*"|'[^']*\bEntityWord\b[^']*')[^>]*>([\s\S]*?)<\/a>/gi,+ (_match, inner: string) => inner.replace(/<[^>]+>/g, ""),+);++const removeNonContent = (html: string) => html+ .replace(/<!--[\s\S]*?-->/g, "")+ .replace(/<(script|style|svg|noscript|iframe|video|audio|canvas|button)\b[\s\S]*?<\/\1>/gi, "")+ .replace(/<(script|style|svg|noscript|iframe|video|audio|canvas|button)\b[^>]*\/?>/gi, "");++export const prepareZhihuHtml = (html: string) => {+ const images: ZhihuImageRef[] = [];+ const seen = new Set<string>();+ let next = removeNonContent(unwrapEntityLinks(html));+ next = next.replace(/<img\b[^>]*>/gi, (tag) => {+ if (images.length >= MAX_ZHIHU_IMAGES) return "";+ const raw = tagAttribute(tag, "data-original")+ || tagAttribute(tag, "data-actualsrc")+ || tagAttribute(tag, "src");+ const url = normalizeZhihuImageUrl(raw);+ if (!url) return "";+ const key = imageKey(url);+ if (seen.has(key)) return "";+ seen.add(key);+ const alt = plainLine(tagAttribute(tag, "data-caption") || tagAttribute(tag, "alt")).slice(0, 120);+ const token = `EDGEVERZHIHUIMG${images.length}`;+ images.push({ url, alt });+ return `\n\n${token}\n\n`;+ });+ return { html: next, images };+};++const normalizeMarkdown = (value: string) => value.replace(/\n{3,}/g, "\n\n").trim();++export const zhihuBodyFromHtml = (html: string, altFallback: string) => {+ const prepared = prepareZhihuHtml(html);+ const turndown = new TurndownService({+ bulletListMarker: "-",+ codeBlockStyle: "fenced",+ headingStyle: "atx",+ linkStyle: "inlined",+ });+ let markdown = normalizeMarkdown(turndown.turndown(prepared.html));+ prepared.images.forEach((image, index) => {+ const alt = escapeImageAlt(image.alt || altFallback);+ markdown = markdown.replaceAll(`EDGEVERZHIHUIMG${index}`, ``);+ });+ return { markdown: normalizeMarkdown(markdown), images: prepared.images };+};++export const replaceZhihuImageUrls = (+ markdown: string,+ images: Array<{ url: string; resourceId: string }>,+) => {+ let next = markdown;+ for (const image of images) {+ if (!image.url || !image.resourceId) continue;+ const local = `/api/v1/resources/${encodeURIComponent(image.resourceId)}/blob`;+ next = next.replaceAll(`](${image.url})`, `](${local})`);+ }+ return next;+};++const isKind = (value: unknown): value is ZhihuKind => value === "answer" || value === "article";++export const isZhihuLocate = (value: unknown): value is ZhihuLocate => {+ if (!value || typeof value !== "object") return false;+ const record = value as Partial<ZhihuLocateSuccess> & Partial<ZhihuLocateFailure>;+ if (record.ok === false) return record.reason === "not-found" || record.reason === "needs-listener";+ if (record.ok !== true || !isKind(record.kind)) return false;+ return typeof record.id === "string"+ && typeof record.questionId === "string"+ && typeof record.title === "string"+ && typeof record.author === "string"+ && typeof record.href === "string"+ && typeof record.pageUrl === "string"+ && typeof record.domHtml === "string"+ && typeof record.domComplete === "boolean";+};++export const isZhihuApiRead = (value: unknown): value is ZhihuApiRead => {+ if (!value || typeof value !== "object") return false;+ const record = value as Partial<ZhihuApiSuccess> & Partial<ZhihuApiFailure>;+ if (record.ok === false) return record.reason === "unreadable";+ if (record.ok !== true || !isKind(record.kind)) return false;+ return typeof record.id === "string"+ && typeof record.title === "string"+ && typeof record.author === "string"+ && typeof record.html === "string"+ && typeof record.questionId === "string"+ && typeof record.timeSeconds === "number"+ && typeof record.truncated === "boolean";+};++export const resolveZhihuNote = (+ located: ZhihuLocateSuccess,+ api: ZhihuApiRead | null,+): ResolvedZhihuNote | null => {+ const fetched = api?.ok ? api : null;+ const apiHtml = fetched?.html.trim() ?? "";+ const domHtml = located.domComplete ? located.domHtml.trim() : "";+ const useDom = Boolean(domHtml) && (!apiHtml || Boolean(fetched?.truncated && domHtml.length > apiHtml.length));+ const html = useDom ? domHtml : apiHtml;+ const title = plainLine(fetched?.title || located.title);+ const author = plainLine(fetched?.author || located.author);+ if (!html) return null;+ const questionId = /^\d+$/.test(fetched?.questionId || "")+ ? fetched?.questionId || ""+ : located.questionId;+ const target: ZhihuTarget = { kind: located.kind, id: located.id, questionId };+ const noteUrl = canonicalZhihuUrl(target);+ if (!noteUrl) return null;+ return {+ ...target,+ title,+ author,+ html,+ timeSeconds: fetched?.timeSeconds && fetched.timeSeconds > 0 ? fetched.timeSeconds : 0,+ noteUrl,+ };+};++export const zhihuNoteTitle = (input: { title: string; author: string; body: string; fallback: string }) => {+ const heading = plainLine(input.title);+ if (heading) return heading.slice(0, 160);+ const first = input.body.split("\n").map((line) => line.replace(/^!\[[^\]]*]\([^)]*\)$/, "").trim()).find(Boolean) ?? "";+ const name = plainLine(input.author);+ const combined = name && first ? `${name}: ${first}` : (first || name || input.fallback);+ return plainLine(combined).slice(0, 160);+};++export const zhihuNoteMarkdown = (input: {+ author: string;+ title: string;+ body: string;+ noteUrl: string;+ datetime: string;+ capturedAt: string;+ sourceLabel: string;+ capturedAtLabel: string;+ timeLabel: string;+}) => {+ const blocks: string[] = [];+ const author = plainLine(input.author);+ if (author) blocks.push(author);+ const title = plainLine(input.title);+ const body = input.body.trim();+ if (title && !body.startsWith(title)) blocks.push(title);+ if (body) blocks.push(body);+ const footer = [+ input.noteUrl ? `${input.sourceLabel}: [${escapeMarkdownLabel(input.noteUrl)}](${markdownDestination(input.noteUrl)})` : "",+ input.datetime ? `${input.timeLabel}: ${input.datetime}` : "",+ `${input.capturedAtLabel}: ${input.capturedAt}`,+ ].filter(Boolean);+ blocks.push(footer.join("\n\n"));+ return blocks.join("\n\n");+};++export const saveCapturedZhihuNote = async (+ client: ImageNoteClient,+ input: {+ notebookId: string;+ title: string;+ author: string;+ noteTitle: string;+ body: string;+ noteUrl: string;+ datetime: string;+ images: Array<{ bytes: Uint8Array; mimeType: string; filename: string; alt: string; sourceUrl: string }>;+ capturedAt: string;+ sourceLabel: string;+ capturedAtLabel: string;+ timeLabel: string;+ },+) => {+ let notebookId = input.notebookId;+ if (!notebookId) {+ const listed = await client.listNotebooks();+ notebookId = listed.notebooks[0]?.id ?? "";+ }+ if (!notebookId) throw new Error("no-notebook");++ const markdownFor = (uploaded: Array<{ url: string; resourceId: string }>) => zhihuNoteMarkdown({+ author: input.author,+ title: input.noteTitle,+ body: replaceZhihuImageUrls(input.body, uploaded),+ noteUrl: input.noteUrl,+ datetime: input.datetime,+ capturedAt: input.capturedAt,+ sourceLabel: input.sourceLabel,+ capturedAtLabel: input.capturedAtLabel,+ timeLabel: input.timeLabel,+ });+ const created = await client.createMemo({+ notebookId,+ title: input.title,+ contentMarkdown: markdownFor([]),+ tags: ["web-clip"],+ });+ const memoId = created.memo.id;+ if (!memoId) throw new Error("create-missing-id");+ if (input.images.length === 0) return { memoId, resourceIds: [] as string[] };++ const uploaded: Array<{ url: string; resourceId: string }> = [];+ for (const image of input.images) {+ try {+ const resource = await client.uploadImage(memoId, image);+ if (resource.id && image.sourceUrl) uploaded.push({ url: image.sourceUrl, resourceId: resource.id });+ } catch {+ // The note still keeps the remote image address when one upload fails.+ }+ }+ if (uploaded.length === 0) return { memoId, resourceIds: [] as string[] };++ try {+ const session = await client.createEditSession(memoId);+ await client.saveMemo(memoId, {+ editSessionId: session.editSession.id,+ expectedRevision: session.editSession.baseRevision,+ expectedContentHash: session.editSession.baseContentHash,+ contentMarkdown: markdownFor(uploaded),+ });+ } catch {+ // Leave the first version in place when attaching images fails.+ }+ return { memoId, resourceIds: uploaded.map((image) => image.resourceId) };+};++// Runs in the page's main world so the request uses the signed-in Zhihu session.+// Keep this function free of closures: Chrome serializes it with toString().+export async function fetchZhihuItemInPage(target: { kind?: unknown; id?: unknown }): Promise<ZhihuApiRead> {+ const asString = (value: unknown) => {+ if (typeof value === "string") return value;+ if (typeof value === "number" && Number.isFinite(value)) return String(Math.trunc(value));+ return "";+ };+ const asNumber = (value: unknown) => (+ typeof value === "number" && Number.isFinite(value) ? value : 0+ );+ const kind = target?.kind === "article" ? "article" : target?.kind === "answer" ? "answer" : "";+ const id = asString(target?.id);+ if (!kind || !/^\d+$/.test(id)) return { ok: false, reason: "unreadable" };+ try {+ const endpoint = kind === "article"+ ? `https://zhuanlan.zhihu.com/api/articles/${id}`+ : `/api/v4/answers/${id}?include=content,author.name,question.title,question.id,created_time,updated_time,content_need_truncated`;+ const response = await fetch(endpoint, {+ credentials: "include",+ headers: { accept: "application/json" },+ });+ if (!response.ok) return { ok: false, reason: "unreadable" };+ const data = await response.json() as Record<string, unknown>;+ const authorRecord = data.author && typeof data.author === "object"+ ? data.author as Record<string, unknown>+ : {};+ const question = data.question && typeof data.question === "object"+ ? data.question as Record<string, unknown>+ : {};+ const updated = asNumber(data.updated_time) || asNumber(data.updated);+ const created = asNumber(data.created_time) || asNumber(data.created);+ return {+ ok: true,+ kind,+ id,+ title: asString(kind === "article" ? data.title : question.title),+ author: asString(authorRecord.name),+ html: asString(data.content),+ questionId: kind === "answer" ? asString(question.id) : "",+ timeSeconds: updated || created,+ truncated: data.content_need_truncated === true,+ };+ } catch {+ return { ok: false, reason: "unreadable" };+ }+}diff --git a/apps/extension/src/zhihu-save.ts b/apps/extension/src/zhihu-save.tsnew file mode 100644index 00000000..7ac4e571--- /dev/null+++ b/apps/extension/src/zhihu-save.ts@@ -0,0 +1,46 @@+import "./styles.css";+import { localizeDocument, t } from "./i18n";++localizeDocument();+document.title = t("zhihuSaveWindowTitle");++const status = document.querySelector<HTMLParagraphElement>("#status");+const allowButton = document.querySelector<HTMLButtonElement>("#allow");++const setStatus = (message: string, kind: "normal" | "error" | "success" = "normal") => {+ if (!status) return;+ status.textContent = message;+ status.dataset.kind = kind;+};++allowButton?.addEventListener("click", () => {+ if (!allowButton) return;+ allowButton.disabled = true;+ void (async () => {+ let granted = false;+ try {+ granted = await chrome.permissions.request({+ origins: [+ "https://www.zhihu.com/*",+ "https://zhihu.com/*",+ "https://zhuanlan.zhihu.com/*",+ "https://www.zhuanlan.zhihu.com/*",+ ],+ });+ } catch {+ granted = false;+ }+ if (!granted) {+ setStatus(t("zhihuPermissionDenied"), "error");+ allowButton.disabled = false;+ return;+ }+ try {+ await chrome.runtime.sendMessage({ type: "activateZhihuTarget" });+ } catch {+ // The page can still be saved on the next right-click after a reload.+ }+ setStatus(t("zhihuPermissionReady"), "success");+ window.setTimeout(() => window.close(), 1600);+ })();+});diff --git a/apps/extension/src/zhihu-target.ts b/apps/extension/src/zhihu-target.tsnew file mode 100644index 00000000..cc0dd663--- /dev/null+++ b/apps/extension/src/zhihu-target.ts@@ -0,0 +1,78 @@+// Content script for zhihu.com and zhuanlan.zhihu.com. It only remembers which+// answer or article was under the pointer so a later menu click can save that+// item. No imports: content scripts are classic scripts, and this file is also+// injected again after the user grants access.+(() => {+ const root = globalThis as typeof globalThis & { __edgeeverZhihuTarget?: boolean };+ if (root.__edgeeverZhihuTarget) return;+ root.__edgeeverZhihuTarget = true;++ // Keep identical to targetFromLocation in zhihu-clip.ts.+ const targetFromLocation = (hostname: string, pathname: string) => {+ const host = hostname.toLowerCase();+ const articleHost = host === "zhuanlan.zhihu.com" || host === "www.zhuanlan.zhihu.com";+ if (articleHost) {+ const article = pathname.match(/^\/p\/(\d+)(?=\/|$)/);+ if (article?.[1]) return { kind: "article" as const, id: article[1], questionId: "" };+ return null;+ }+ const zhihuHost = host === "zhihu.com" || host === "www.zhihu.com";+ if (!zhihuHost) return null;+ const answer = pathname.match(/^\/question\/(\d+)\/answer\/(\d+)(?=\/|$)/);+ if (answer?.[1] && answer?.[2]) return { kind: "answer" as const, id: answer[2], questionId: answer[1] };+ const bare = pathname.match(/^\/answer\/(\d+)(?=\/|$)/);+ if (bare?.[1]) return { kind: "answer" as const, id: bare[1], questionId: "" };+ return null;+ };++ const readItem = (node: Element) => {+ const raw = node.getAttribute("data-zop") || "";+ try {+ const parsed = JSON.parse(raw) as { type?: unknown; itemId?: unknown };+ const kind = parsed.type === "article" || parsed.type === "answer" ? parsed.type : "";+ const id = typeof parsed.itemId === "string" || typeof parsed.itemId === "number"+ ? String(parsed.itemId)+ : "";+ if (kind && /^\d+$/.test(id)) return { kind, id };+ } catch {+ // A card without data-zop can still be an answer or article element.+ }+ const itemProp = node.getAttribute("itemprop");+ const name = node.getAttribute("name") || "";+ if ((itemProp === "answer" || itemProp === "article") && /^\d+$/.test(name)) {+ return { kind: itemProp, id: name };+ }+ return null;+ };++ document.addEventListener("contextmenu", (event) => {+ const rawTarget = event.target;+ const element = rawTarget instanceof Element+ ? rawTarget+ : rawTarget instanceof Node+ ? rawTarget.parentElement+ : null;+ if (!element) return;+ for (const node of document.querySelectorAll("[data-edgeever-zhihu-target]")) {+ node.removeAttribute("data-edgeever-zhihu-target");+ node.removeAttribute("data-edgeever-zhihu-kind");+ node.removeAttribute("data-edgeever-zhihu-id");+ }+ const item = element.closest(".ContentItem");+ if (item) {+ const info = readItem(item);+ if (!info) return;+ item.setAttribute("data-edgeever-zhihu-target", "1");+ item.setAttribute("data-edgeever-zhihu-kind", info.kind);+ item.setAttribute("data-edgeever-zhihu-id", info.id);+ return;+ }+ const post = element.closest("article.Post-Main, .Post-Main");+ if (!post) return;+ const fromPage = targetFromLocation(location.hostname, location.pathname);+ if (!fromPage || fromPage.kind !== "article") return;+ post.setAttribute("data-edgeever-zhihu-target", "1");+ post.setAttribute("data-edgeever-zhihu-kind", fromPage.kind);+ post.setAttribute("data-edgeever-zhihu-id", fromPage.id);+ }, true);+})();diff --git a/apps/extension/vite.config.ts b/apps/extension/vite.config.tsindex 64babad6..1ce861fa 100644--- a/apps/extension/vite.config.ts+++ b/apps/extension/vite.config.ts@@ -35,10 +35,13 @@ export default defineConfig({"capture-tweet": fileURLToPath(new URL("./src/capture-tweet.ts", import.meta.url)),"capture-github": fileURLToPath(new URL("./src/capture-github.ts", import.meta.url)),"capture-xhs": fileURLToPath(new URL("./src/capture-xhs.ts", import.meta.url)),+ "capture-zhihu": fileURLToPath(new URL("./src/capture-zhihu.ts", import.meta.url)),"tweet-target": fileURLToPath(new URL("./src/tweet-target.ts", import.meta.url)),"tweet-save": fileURLToPath(new URL("./tweet-save.html", import.meta.url)),"xhs-target": fileURLToPath(new URL("./src/xhs-target.ts", import.meta.url)),"xhs-save": fileURLToPath(new URL("./xhs-save.html", import.meta.url)),+ "zhihu-target": fileURLToPath(new URL("./src/zhihu-target.ts", import.meta.url)),+ "zhihu-save": fileURLToPath(new URL("./zhihu-save.html", import.meta.url)),},output: {entryFileNames: "assets/[name].js",diff --git a/apps/extension/zhihu-clip.test.mjs b/apps/extension/zhihu-clip.test.mjsnew file mode 100644index 00000000..e59e9a39--- /dev/null+++ b/apps/extension/zhihu-clip.test.mjs@@ -0,0 +1,243 @@+import { readFileSync } from "node:fs";+import { describe, expect, test } from "bun:test";+import {+ canonicalZhihuUrl,+ fetchZhihuItemInPage,+ questionIdFromHref,+ replaceZhihuImageUrls,+ resolveZhihuNote,+ saveCapturedZhihuNote,+ zhihuBodyFromHtml,+ zhihuNoteMarkdown,+ zhihuNoteTitle,+ zhihuTargetFromPageUrl,+ zhihuTimeIso,+} from "./src/zhihu-clip.ts";++const answerId = "2088594131882872928";+const questionId = "2032748057339635056";+const articleId = "2089046649519568283";+const answerUrl = `https://www.zhihu.com/question/${questionId}/answer/${answerId}`;+const articleUrl = `https://zhuanlan.zhihu.com/p/${articleId}`;+const imageUrl = "https://pic3.zhimg.com/v2-44e9d53e8322583db6a429f8014ea55a_r.jpg";++const html = [+ "<p>岸上没有人。<a class=\"RichContent-EntityWord css-1\" href=\"https://zhida.zhihu.com/search?q=1\">潜水员<svg viewBox=\"0 0 1 1\"></svg></a>听见叫声。</p>",+ `<figure><img src="https://pic3.zhimg.com/v2-44e9d53e8322583db6a429f8014ea55a_1440w.jpg" data-caption="岸边" data-original="${imageUrl}"/></figure>`,+ "<img src=\"https://picx.zhimg.com/v2-44e9d53e8322583db6a429f8014ea55a_b.jpg\"/>",+ "<img src=\"https://pic1.zhimg.com/avatar/cat.jpg\"/>",+].join("");++const labels = {+ capturedAt: "2026-10-01T00:00:00.000Z",+ sourceLabel: "来源",+ capturedAtLabel: "抓取时间",+ timeLabel: "时间",+};++const located = {+ ok: true,+ kind: "answer",+ id: answerId,+ questionId,+ title: "预览标题",+ author: "页面作者",+ href: answerUrl,+ pageUrl: "https://www.zhihu.com/",+ domHtml: "<p>折叠预览</p>",+ domComplete: false,+};++describe("zhihu addresses", () => {+ test("reads an answer or article from its page and ignores a feed or question list", () => {+ expect(zhihuTargetFromPageUrl(answerUrl)).toEqual({ kind: "answer", id: answerId, questionId });+ expect(zhihuTargetFromPageUrl(`https://zhihu.com/answer/${answerId}?utm=1`)).toEqual({+ kind: "answer",+ id: answerId,+ questionId: "",+ });+ expect(zhihuTargetFromPageUrl(`${articleUrl}?utm=1`)).toEqual({+ kind: "article",+ id: articleId,+ questionId: "",+ });+ expect(zhihuTargetFromPageUrl("https://www.zhihu.com/")).toBeNull();+ expect(zhihuTargetFromPageUrl(`https://www.zhihu.com/question/${questionId}`)).toBeNull();+ expect(zhihuTargetFromPageUrl("https://zhuanlan.zhihu.com/c_123")).toBeNull();+ expect(zhihuTargetFromPageUrl("https://x.com/home")).toBeNull();+ expect(questionIdFromHref(`//www.zhihu.com/question/${questionId}/answer/${answerId}`)).toBe(questionId);+ expect(canonicalZhihuUrl({ kind: "answer", id: answerId, questionId })).toBe(answerUrl);+ expect(canonicalZhihuUrl({ kind: "article", id: articleId, questionId: "" })).toBe(articleUrl);+ expect(canonicalZhihuUrl({ kind: "answer", id: "nope", questionId })).toBe("");+ });+});++describe("zhihu note content", () => {+ test("keeps the answer text, original photo, author, and canonical link", () => {+ expect(zhihuTimeIso(1790739645)).toBe("2026-09-30T03:40:45.000Z");+ const body = zhihuBodyFromHtml(html, "图片");+ expect(body.markdown).toContain("岸上没有人。潜水员听见叫声。");+ expect(body.markdown).not.toContain("zhida.zhihu.com");+ expect(body.markdown).not.toContain("<svg");+ expect(body.images.map((image) => image.url)).toEqual([imageUrl]);+ expect(body.images[0]?.alt).toBe("岸边");+ expect(body.markdown).toContain(``);+ const resolved = resolveZhihuNote(located, {+ ok: true,+ kind: "answer",+ id: answerId,+ title: "谁叫我上来的?",+ author: "苏澄宇",+ html,+ questionId,+ timeSeconds: 1790739645,+ truncated: false,+ });+ expect(resolved?.noteUrl).toBe(answerUrl);+ expect(resolved?.author).toBe("苏澄宇");+ const markdown = zhihuNoteMarkdown({+ ...labels,+ author: resolved.author,+ title: resolved.title,+ body: body.markdown,+ noteUrl: resolved.noteUrl,+ datetime: zhihuTimeIso(resolved.timeSeconds),+ });+ expect(markdown.startsWith("苏澄宇")).toBe(true);+ expect(markdown).toContain("谁叫我上来的?");+ expect(markdown).toContain(`(${answerUrl})`);+ expect(markdown).toContain("时间: 2026-09-30T03:40:45.000Z");+ expect(replaceZhihuImageUrls(markdown, [{ url: imageUrl, resourceId: "res 1" }])).toContain(+ "",+ );+ expect(replaceZhihuImageUrls(markdown, [{ url: imageUrl, resourceId: "res 1" }])).not.toContain("zhimg.com");+ expect(zhihuNoteTitle({ title: "", author: "苏澄宇", body: "岸上没有人。", fallback: "一篇知乎内容" }))+ .toBe("苏澄宇: 岸上没有人。");+ });++ test("uses the open page when the api content is missing or shorter than a truncated copy", () => {+ expect(resolveZhihuNote({ ...located, domComplete: false, domHtml: "<p>只有预览</p>" }, {+ ok: false,+ reason: "unreadable",+ })).toBeNull();+ const fromPage = resolveZhihuNote({+ ...located,+ kind: "article",+ id: articleId,+ questionId: "",+ title: "专栏标题",+ author: "页面作者",+ domHtml: "<p>页面上的全文</p>",+ domComplete: true,+ }, { ok: false, reason: "unreadable" });+ expect(fromPage?.html).toBe("<p>页面上的全文</p>");+ expect(fromPage?.noteUrl).toBe(articleUrl);+ const longerPage = resolveZhihuNote({+ ...located,+ domHtml: "<p>展开后的更长正文</p>",+ domComplete: true,+ }, {+ ok: true,+ kind: "answer",+ id: answerId,+ title: "接口标题",+ author: "接口作者",+ html: "<p>短</p>",+ questionId,+ timeSeconds: 10,+ truncated: true,+ });+ expect(longerPage?.html).toBe("<p>展开后的更长正文</p>");+ expect(longerPage?.title).toBe("接口标题");+ });++ test("reads the zhihu api in the page world without extension helpers", () => {+ const source = fetchZhihuItemInPage.toString();+ expect(source).toContain("/api/v4/answers/");+ expect(source).toContain("https://zhuanlan.zhihu.com/api/articles/");+ expect(source).not.toContain("prepareZhihuHtml");+ expect(source).not.toContain("resolveZhihuNote");+ expect(source).not.toContain("zhihuTargetFromPageUrl");+ });++ test("keeps the address parsers identical in the page scripts", () => {+ const library = readFileSync(new URL("./src/zhihu-clip.ts", import.meta.url), "utf8");+ const parser = library.match(/const targetFromLocation = \(hostname: string, pathname: string\) => \{[\s\S]*?\n\};/);+ const question = library.match(/export const questionIdFromHref = \(href: string\) => \{[\s\S]*?\n\};/);+ const compact = (source) => source.replace(/^export /gm, "").replace(/^[ \t]+/gm, "");+ expect(parser?.[0]).toBeTruthy();+ expect(question?.[0]).toBeTruthy();+ for (const file of ["./src/capture-zhihu.ts", "./src/zhihu-target.ts"]) {+ const page = readFileSync(new URL(file, import.meta.url), "utf8");+ expect(compact(page)).toContain(compact(parser[0]));+ }+ const capture = readFileSync(new URL("./src/capture-zhihu.ts", import.meta.url), "utf8");+ expect(compact(capture)).toContain(compact(question[0]));+ const background = readFileSync(new URL("./src/background.ts", import.meta.url), "utf8");+ const patterns = background.slice(+ background.indexOf("const ZHIHU_DOCUMENT_PATTERNS"),+ background.indexOf("const ZHIHU_DOCUMENT_PATTERNS") + 320,+ );+ const block = background.slice(background.indexOf("id: ZHIHU_MENU_ID"), background.indexOf("id: ZHIHU_MENU_ID") + 320);+ expect(patterns).toContain("https://www.zhihu.com/*");+ expect(patterns).toContain("https://zhuanlan.zhihu.com/*");+ expect(block).toContain('contexts: ["page", "video"]');+ expect(block).toContain("documentUrlPatterns: ZHIHU_DOCUMENT_PATTERNS");+ expect(block).not.toContain("selection");+ expect(block).not.toContain('"image"');+ });+});++describe("saveCapturedZhihuNote", () => {+ const client = () => {+ const calls = { created: null, saved: null };+ return {+ calls,+ api: {+ listNotebooks: async () => ({ notebooks: [{ id: "nb_first" }] }),+ createMemo: async (body) => {+ calls.created = body;+ return { memo: { id: "memo_1" } };+ },+ uploadImage: async () => ({ id: "res_1" }),+ createEditSession: async () => ({+ editSession: { id: "edit_1", baseRevision: 3, baseContentHash: "a".repeat(64) },+ }),+ saveMemo: async (_memoId, body) => {+ calls.saved = body;+ return {};+ },+ deleteMemo: async () => ({}),+ createWithImage: async () => ({ memoId: "memo_1", resourceId: "res_1" }),+ },+ };+ };++ test("creates the note with the remote photo, then rewrites a successful upload", async () => {+ const fixture = client();+ const saved = await saveCapturedZhihuNote(fixture.api, {+ notebookId: "",+ title: "谁叫我上来的?",+ author: "苏澄宇",+ noteTitle: "谁叫我上来的?",+ body: `岸上没有人。\n\n`,+ noteUrl: answerUrl,+ datetime: "2026-09-30T03:40:45.000Z",+ images: [{+ bytes: new Uint8Array([1, 2, 3]),+ mimeType: "image/jpeg",+ filename: "shore.jpg",+ alt: "岸边",+ sourceUrl: imageUrl,+ }],+ ...labels,+ });+ expect(saved).toEqual({ memoId: "memo_1", resourceIds: ["res_1"] });+ expect(fixture.calls.created.notebookId).toBe("nb_first");+ expect(fixture.calls.created.tags).toEqual(["web-clip"]);+ expect(fixture.calls.created.contentMarkdown).toContain(imageUrl);+ expect(fixture.calls.saved.contentMarkdown).toContain("");+ expect(fixture.calls.saved.contentMarkdown).not.toContain("zhimg.com");+ expect(fixture.calls.saved.expectedRevision).toBe(3);+ });+});diff --git a/apps/extension/zhihu-save.html b/apps/extension/zhihu-save.htmlnew file mode 100644index 00000000..e28f3613--- /dev/null+++ b/apps/extension/zhihu-save.html@@ -0,0 +1,19 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title data-i18n="zhihuSaveWindowTitle">Save this Zhihu answer or article to EdgeEver</title>+ </head>+ <body>+ <main class="image-save-shell">+ <h1 data-i18n="zhihuSaveWindowTitle">Save this Zhihu answer or article to EdgeEver</h1>+ <p class="hint" data-i18n="zhihuPermissionIntro">A feed lists many answers and articles. Allow access to Zhihu so the clipper can remember the one under the pointer. After that, right-click the same text once more. Only the answer or article you choose is saved to the clipper's default notebook.</p>+ <div class="image-save-actions">+ <button id="allow" type="button" data-i18n="allowZhihuAccess">Allow access to Zhihu</button>+ </div>+ <p id="status" class="status" role="status"></p>+ </main>+ <script type="module" src="/src/zhihu-save.ts"></script>+ </body>+</html>