Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

feat(extension): save Reddit posts from context menu

tianma-ifd726122d22db
diff --git a/apps/extension/FIREFOX_STORE_LISTING.md b/apps/extension/FIREFOX_STORE_LISTING.md
index b8eee987..e0c5fb12 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, a Zhihu answer or article, or a GitHub repository to your EdgeEver instance.
+- Summary: Save a webpage, selected text, an image, an X post, a Reddit 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,13 +11,14 @@
## Description
-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.
+EdgeEver Web Clipper saves the current webpage, selected text, a right-clicked image, an X post, a Reddit 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 Reddit, right-click a post and save its title, author, community, text, links, and images. Comments are left out.
- 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.
@@ -25,7 +26,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 post to EdgeEver**, **Save note to EdgeEver**, **Save answer or article to EdgeEver**, or **Save repository info 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 choose a clip or save command, including **Save Reddit post to EdgeEver**.
## Data collection and transmission
@@ -48,7 +49,8 @@ The project maintainers do not receive or retain this data. Instance settings ar
9. Open one GitHub repository page, right-click the description or README text, choose **Save repository info 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 note to EdgeEver**, and verify the note contains the title, text, and source link.
11. Open one Zhihu answer or article, right-click the text (not a photo), choose **Save 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.
+12. Open one Reddit post, right-click the post text, choose **Save Reddit post to EdgeEver**, and verify the note contains the title, author, community, and source link without comments.
+13. 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.
@@ -72,17 +74,18 @@ The reviewable source is the repository source before Vite bundling. Third-party
## 中文商店说明
-EdgeEver 网页剪藏插件可将当前网页、选中的文字、右键选中的图片、X 上的一条推文、小红书上的一篇笔记,或知乎上的一篇回答或文章直接保存到用户配置的自托管 EdgeEver 实例。
+EdgeEver 网页剪藏插件可将当前网页、选中的文字、右键选中的图片、X 上的一条推文、Reddit 上的一条帖子、小红书上的一篇笔记,或知乎上的一篇回答或文章直接保存到用户配置的自托管 EdgeEver 实例。
- 提取适合阅读的文章正文。选中文字后右键,只保存这一段。
- 在图片上右键,把图片文件存成一条新笔记。从 Google 搜索保存时,笔记记录“Google 搜索”和关键词。
- 在 X 上右键推文正文。长文会先展开“显示更多”,再保存全文和已经显示的图片。
- 在小红书笔记正文上右键,保存标题、正文和图片。评论不会写入。
- 在知乎回答或文章正文上右键,保存标题、作者、正文和图片。评论不会写入。首页和问题页保存的是指针下的那一篇。
+- 在 Reddit 帖子正文上右键,保存标题、作者、社区、正文、链接和图片,不写入评论。
- 这些命令直接出现在右键菜单的第一级。
- 在浏览器本地将 HTML 转换为 Markdown。
- 可选择默认 EdgeEver 笔记本。
- 数据直接发送到用户自己的实例,不经过 EdgeEver 中转服务。
- 不包含广告、分析、追踪或遥测。
-使用前,请在插件设置中填写 EdgeEver 实例地址和 API Token。插件只会在用户点击“剪藏当前网页”,或选择“保存所选内容到 EdgeEver”“保存图片到 EdgeEver”“保存推文到 EdgeEver”“保存笔记到 EdgeEver”“保存回答/文章到 EdgeEver”后读取并发送网页内容。
+使用前,请在插件设置中填写 EdgeEver 实例地址和 API Token。插件只会在用户选择剪藏或保存命令(包括“保存 Reddit 帖子到 EdgeEver”)后读取并发送网页内容。
diff --git a/apps/extension/README.md b/apps/extension/README.md
index 762fdf06..4e6519d4 100644
--- a/apps/extension/README.md
+++ b/apps/extension/README.md
@@ -13,6 +13,7 @@ Chrome, Edge, and Firefox Manifest V3 extension for saving the current webpage,
- 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 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 Zhihu content 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 Reddit, right-click a post or its title link and choose **Save Reddit post to EdgeEver**. The selected post becomes one note with its title, author, community, post text, source link, linked page, and available images. Comments are left out. The extension reads the selected post through Reddit's JSON response when available and falls back to its visible content. If the pointer listener is unavailable on a feed, right-click the same post 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.md
index c2cbc1ff..31300eb3 100644
--- a/apps/extension/STORE_LISTING.md
+++ b/apps/extension/STORE_LISTING.md
@@ -29,7 +29,7 @@ The detailed descriptions below are the 0.1.9 text resubmitted on 2026-10-02. An
#### Summary
-将当前网页、选中文字、右键图片、X 推文、小红书笔记、知乎回答或文章,或 GitHub 仓库保存到你自托管的 EdgeEver 实例。
+将当前网页、选中文字、右键图片、X 推文、Reddit 帖子、小红书笔记、知乎回答或文章,或 GitHub 仓库保存到你自托管的 EdgeEver 实例。
#### Detailed description
@@ -43,6 +43,7 @@ EdgeEver Web Clipper 可以把当前网页,或你选中的那一部分,保
- 在 X 上右键推文,保存展开后的全文和已经显示的图片。
- 在小红书上保存笔记的标题、正文和图片,不写入评论。
- 在知乎上保存指针下的回答或文章,包括标题、作者、正文和图片,不写入评论。
+- 在 Reddit 上右键帖子,保存标题、作者、社区、正文、链接和图片,不写入评论。
- 在 GitHub 仓库页上保存地址和简介;页面上有主页、语言、许可证和话题时一并写入。
- 这些命令直接出现在右键菜单的第一级。
- 笔记会保留来源和剪藏时间。
@@ -57,7 +58,7 @@ EdgeEver 是开源、自托管的现代笔记工作区。项目主页与源代
#### Summary
-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.
+Save a webpage, selected text, a right-clicked image, an X post, a Reddit post, a Xiaohongshu note, a Zhihu answer or article, or a GitHub repository to your self-hosted EdgeEver.
#### Detailed description
@@ -71,6 +72,7 @@ Key features:
- On X, right-click the post and save the expanded text with the photos already shown.
- On Xiaohongshu, save the note title, text, and photos. Comments are left out.
- On Zhihu, save the answer or article under the pointer, including its title, author, text, and photos. Comments are left out.
+- On Reddit, right-click a post to save its title, author, community, text, links, and images. Comments are left out.
- On a GitHub repository page, save 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.
- The note keeps its source and the time it was clipped.
@@ -85,15 +87,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, one Zhihu answer or article, 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 Reddit 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 post to EdgeEver, Save note to EdgeEver, Save answer or article to EdgeEver, or Save repository info 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.
+- `activeTab`: Read the active page only after the user clicks the extension's save action or chooses a save command for selected text, an image, an X post, a Reddit post, a Xiaohongshu note, a Zhihu item, or a GitHub repository.
+- `contextMenus`: Add one top-level item for the thing the user right-clicked: selected text, an image, an X post, a Reddit 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: API calls go only to the EdgeEver instance the user approves. If a page cannot provide an image file, the extension asks for that image's site, or for all sites when the user chooses that option, and uses the access only to download the chosen image. Saving from an X timeline asks for access to X so the extension can remember the post under the pointer. That script only records the target and runs after the user allows it. Saving from a Xiaohongshu feed asks for Xiaohongshu for the same reason. An open note page can be saved without that extra permission. On Zhihu, a content script remembers the answer or article under the pointer and does not send the page anywhere. The full text is read only after the user chooses Save Zhihu content to EdgeEver, and it is sent only to the user's instance. If that listener is missing, the extension asks once for Zhihu and then asks the user to right-click the same text again.
+- Optional host permissions: API calls go only to the EdgeEver instance the user approves. If a page cannot provide an image file, the extension asks for that image's site, or for all sites when the user chooses that option, and uses the access only to download the chosen image. Saving from an X or Xiaohongshu feed may ask for site access to identify the item under the pointer. On Zhihu and Reddit, a content script only remembers the item under the pointer. Its content is read after the user chooses the save command. If that listener is unavailable, the extension asks the user to right-click the same item again.
Each permission justification field accepts at most 1,000 characters. The host text above is the wording saved with the 0.1.9 draft.
diff --git a/apps/extension/context-menus.test.mjs b/apps/extension/context-menus.test.mjs
index 61372998..82262c0b 100644
--- a/apps/extension/context-menus.test.mjs
+++ b/apps/extension/context-menus.test.mjs
@@ -41,6 +41,8 @@ test("registers context menus on install, not on background startup", async () =
"save-github-repo",
"save-xhs",
"save-zhihu",
+ "save-reddit",
+ "save-reddit-link",
]);
expect(created.find((item) => item.id === "save-xhs")).toMatchObject({
contexts: ["page", "video"],
@@ -55,6 +57,26 @@ test("registers context menus on install, not on background startup", async () =
"https://www.zhuanlan.zhihu.com/*",
],
});
+ expect(created.find((item) => item.id === "save-reddit")).toMatchObject({
+ contexts: ["page", "video"],
+ documentUrlPatterns: [
+ "https://reddit.com/*",
+ "https://www.reddit.com/*",
+ "https://old.reddit.com/*",
+ "https://new.reddit.com/*",
+ "https://sh.reddit.com/*",
+ ],
+ });
+ expect(created.find((item) => item.id === "save-reddit-link")).toMatchObject({
+ contexts: ["link"],
+ targetUrlPatterns: [
+ "https://reddit.com/*/comments/*",
+ "https://www.reddit.com/*/comments/*",
+ "https://old.reddit.com/*/comments/*",
+ "https://new.reddit.com/*/comments/*",
+ "https://sh.reddit.com/*/comments/*",
+ ],
+ });
} finally {
globalThis.chrome = previousChrome;
}
diff --git a/apps/extension/manifest.base.json b/apps/extension/manifest.base.json
index 06a68e61..39bf0eae 100644
--- a/apps/extension/manifest.base.json
+++ b/apps/extension/manifest.base.json
@@ -49,6 +49,17 @@
],
"js": ["assets/zhihu-target.js"],
"run_at": "document_start"
+ },
+ {
+ "matches": [
+ "https://reddit.com/*",
+ "https://www.reddit.com/*",
+ "https://old.reddit.com/*",
+ "https://new.reddit.com/*",
+ "https://sh.reddit.com/*"
+ ],
+ "js": ["assets/reddit-target.js"],
+ "run_at": "document_start"
}
]
}
diff --git a/apps/extension/manifest.test.mjs b/apps/extension/manifest.test.mjs
index e75a92ea..c6d62ece 100644
--- a/apps/extension/manifest.test.mjs
+++ b/apps/extension/manifest.test.mjs
@@ -49,6 +49,17 @@ describe("extension manifests", () => {
js: ["assets/zhihu-target.js"],
run_at: "document_start",
},
+ {
+ matches: [
+ "https://reddit.com/*",
+ "https://www.reddit.com/*",
+ "https://old.reddit.com/*",
+ "https://new.reddit.com/*",
+ "https://sh.reddit.com/*",
+ ],
+ js: ["assets/reddit-target.js"],
+ run_at: "document_start",
+ },
]);
}
});
diff --git a/apps/extension/package.json b/apps/extension/package.json
index e6cfb706..fdccc1ea 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 context-menus.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"
+ "test": "bun test manifest.test.mjs context-menus.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 reddit-clip.test.mjs"
},
"dependencies": {
"@mixmark-io/domino": "2.2.0",
diff --git a/apps/extension/public/_locales/en/messages.json b/apps/extension/public/_locales/en/messages.json
index c5056b94..9e338886 100644
--- a/apps/extension/public/_locales/en/messages.json
+++ b/apps/extension/public/_locales/en/messages.json
@@ -461,5 +461,29 @@
},
"zhihuSaveWindowTitle": {
"message": "Save answer or article to EdgeEver"
+ },
+ "saveRedditToEdgeEver": {
+ "message": "Save Reddit post to EdgeEver"
+ },
+ "savingReddit": {
+ "message": "Saving this Reddit post…"
+ },
+ "redditSaved": {
+ "message": "Saved this Reddit post as a note."
+ },
+ "redditNotFound": {
+ "message": "Could not find that Reddit post. Right-click directly on a post."
+ },
+ "redditRightClickAgain": {
+ "message": "Reddit posts can be recognized now. Right-click that post again."
+ },
+ "redditAuthorLabel": {
+ "message": "Author"
+ },
+ "redditCommunityLabel": {
+ "message": "Community"
+ },
+ "redditLinkLabel": {
+ "message": "Linked page"
}
}
diff --git a/apps/extension/public/_locales/ja/messages.json b/apps/extension/public/_locales/ja/messages.json
index 8be3feca..b1d72e69 100644
--- a/apps/extension/public/_locales/ja/messages.json
+++ b/apps/extension/public/_locales/ja/messages.json
@@ -461,5 +461,29 @@
},
"zhihuSaveWindowTitle": {
"message": "回答・記事を EdgeEver に保存"
+ },
+ "saveRedditToEdgeEver": {
+ "message": "Reddit の投稿を EdgeEver に保存"
+ },
+ "savingReddit": {
+ "message": "Reddit の投稿を保存しています…"
+ },
+ "redditSaved": {
+ "message": "Reddit の投稿をノートに保存しました。"
+ },
+ "redditNotFound": {
+ "message": "Reddit の投稿が見つかりません。投稿の上で右クリックしてください。"
+ },
+ "redditRightClickAgain": {
+ "message": "Reddit の投稿を認識できるようになりました。同じ投稿をもう一度右クリックしてください。"
+ },
+ "redditAuthorLabel": {
+ "message": "投稿者"
+ },
+ "redditCommunityLabel": {
+ "message": "コミュニティ"
+ },
+ "redditLinkLabel": {
+ "message": "外部リンク"
}
}
diff --git a/apps/extension/public/_locales/zh_CN/messages.json b/apps/extension/public/_locales/zh_CN/messages.json
index 83b32229..13ae1a12 100644
--- a/apps/extension/public/_locales/zh_CN/messages.json
+++ b/apps/extension/public/_locales/zh_CN/messages.json
@@ -461,5 +461,29 @@
},
"zhihuSaveWindowTitle": {
"message": "保存回答/文章到 EdgeEver"
+ },
+ "saveRedditToEdgeEver": {
+ "message": "保存 Reddit 帖子到 EdgeEver"
+ },
+ "savingReddit": {
+ "message": "正在保存这条 Reddit 帖子……"
+ },
+ "redditSaved": {
+ "message": "已把这条 Reddit 帖子存成笔记。"
+ },
+ "redditNotFound": {
+ "message": "没有定位到这条 Reddit 帖子。请直接在帖子上右键。"
+ },
+ "redditRightClickAgain": {
+ "message": "现在可以识别 Reddit 帖子了。请在同一条帖子上再次右键。"
+ },
+ "redditAuthorLabel": {
+ "message": "作者"
+ },
+ "redditCommunityLabel": {
+ "message": "社区"
+ },
+ "redditLinkLabel": {
+ "message": "外部链接"
}
}
diff --git a/apps/extension/reddit-clip.test.mjs b/apps/extension/reddit-clip.test.mjs
new file mode 100644
index 00000000..6805ecdf
--- /dev/null
+++ b/apps/extension/reddit-clip.test.mjs
@@ -0,0 +1,72 @@
+import { describe, expect, test } from "bun:test";
+import {
+ redditCanonicalUrl, redditPostFromApi, redditPostFromDom,
+ redditPostIdFromUrl, redditPostMarkdown, saveCapturedRedditPost,
+} from "./src/reddit-clip.ts";
+
+const postId = "1abcxyz";
+const source = `https://www.reddit.com/r/AskReddit/comments/${postId}/`;
+const photo = "https://i.redd.it/photo.jpg";
+const listing = (data) => [{ data: { children: [{ kind: "t3", data: { id: postId, ...data } }] } }, { data: { children: [] } }];
+const labels = {
+ sourceLabel: "Source", capturedAtLabel: "Captured", timeLabel: "Time",
+ authorLabel: "Author", communityLabel: "Community", linkLabel: "Linked page",
+ capturedAt: "2026-10-03T00:00:00.000Z",
+};
+
+describe("Reddit post capture", () => {
+ test("recognizes only Reddit post URLs and keeps one canonical link", () => {
+ expect(redditPostIdFromUrl(`https://old.reddit.com/r/AskReddit/comments/${postId}/slug?utm=1`)).toBe(postId);
+ expect(redditPostIdFromUrl("https://www.reddit.com/r/AskReddit/")).toBe("");
+ expect(redditPostIdFromUrl(`https://example.com/comments/${postId}/`)).toBe("");
+ expect(redditCanonicalUrl(postId, "r/AskReddit")).toBe(source);
+ });
+
+ test("reads full text, gallery images, author, community, and post time from post JSON", () => {
+ const post = redditPostFromApi(listing({
+ title: "How does this work?", author: "sample_user", subreddit: "AskReddit",
+ selftext: "First paragraph.\n\nSecond paragraph.", created_utc: 1790985600,
+ gallery_data: { items: [{ media_id: "one", caption: "A photo" }] },
+ media_metadata: { one: { s: { u: "https://i.redd.it/photo.jpg?width=100&format=pjpg" } } },
+ }), postId);
+ expect(post).toMatchObject({
+ id: postId, url: source, author: "sample_user", subreddit: "r/AskReddit",
+ body: "First paragraph.\n\nSecond paragraph.",
+ });
+ expect(post.images).toEqual([{ url: "https://i.redd.it/photo.jpg?width=100&format=pjpg", alt: "A photo" }]);
+ expect(redditPostFromApi(listing({ title: "Wrong" }), "another")).toBeNull();
+ const markdown = redditPostMarkdown(post, labels);
+ expect(markdown).toContain("Community: r/AskReddit");
+ expect(markdown).toContain("Author: u/sample_user");
+ expect(markdown).toContain("First paragraph.\n\nSecond paragraph.");
+ expect(markdown).toContain(`Source: [${source}](${source})`);
+ expect(markdown).toContain("![A photo](https://i.redd.it/photo.jpg?width=100&format=pjpg)");
+ });
+
+ test("uses only the selected post DOM when Reddit JSON is unavailable", () => {
+ const post = redditPostFromDom({
+ id: postId, title: "Selected post", author: "u/author", subreddit: "r/test",
+ body: "Only this post", externalUrl: "https://example.com/article", datetime: "2026-10-02",
+ images: [{ url: photo, alt: "Photo" }, { url: "javascript:alert(1)", alt: "Bad" }],
+ }, postId);
+ expect(post).toMatchObject({ title: "Selected post", author: "author", url: "https://www.reddit.com/r/test/comments/1abcxyz/" });
+ expect(post.images).toEqual([{ url: photo, alt: "Photo" }]);
+ expect(redditPostFromDom({ id: "other", title: "Wrong post" }, postId)).toBeNull();
+ });
+
+ test("saves remote image links first and replaces them after an upload", async () => {
+ const calls = [];
+ const client = {
+ listNotebooks: async () => ({ notebooks: [{ id: "nb" }] }),
+ createMemo: async (body) => { calls.push(["create", body]); return { memo: { id: "memo" } }; },
+ uploadImage: async () => ({ id: "res 1" }),
+ createEditSession: async () => ({ editSession: { id: "edit", baseRevision: 1, baseContentHash: "hash" } }),
+ saveMemo: async (_id, body) => { calls.push(["save", body]); },
+ };
+ const post = redditPostFromApi(listing({ title: "Picture", subreddit: "pics", url_overridden_by_dest: photo }), postId);
+ await saveCapturedRedditPost(client, post, { ...labels, notebookId: "", images: [{ url: photo, bytes: new Uint8Array([1]), mimeType: "image/jpeg", filename: "photo.jpg", alt: "Photo" }] });
+ expect(calls[0][1].contentMarkdown).toContain(photo);
+ expect(calls[1][1].contentMarkdown).toContain("/api/v1/resources/res%201/blob");
+ expect(calls[1][1].contentMarkdown).not.toContain(photo);
+ });
+});
diff --git a/apps/extension/src/background.ts b/apps/extension/src/background.ts
index 4a6267f1..418d32b6 100644
--- a/apps/extension/src/background.ts
+++ b/apps/extension/src/background.ts
@@ -36,6 +36,11 @@ import {
selectionNoteMarkdown,
selectionNoteTitle,
} from "./selection-clip";
+import {
+ redditPostFromApi,
+ redditPostFromDom,
+ saveCapturedRedditPost,
+} from "./reddit-clip";
import {
canonicalStatusUrl,
isCapturedTweet,
@@ -119,6 +124,15 @@ const ZHIHU_DOCUMENT_PATTERNS = [
"https://zhuanlan.zhihu.com/*",
"https://www.zhuanlan.zhihu.com/*",
];
+const REDDIT_MENU_ID = "save-reddit";
+const REDDIT_LINK_MENU_ID = "save-reddit-link";
+const REDDIT_DOCUMENT_PATTERNS = [
+ "https://reddit.com/*",
+ "https://www.reddit.com/*",
+ "https://old.reddit.com/*",
+ "https://new.reddit.com/*",
+ "https://sh.reddit.com/*",
+];
const toMarkdown = (page: CapturedPage) => {
const capturedAt = new Date().toISOString();
@@ -444,6 +458,7 @@ 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>();
+const pendingRedditReads = new Map<string, (result: unknown) => void>();
let clipQueue = Promise.resolve();
let completingImageSave = false;
@@ -978,6 +993,86 @@ const saveZhihuFromMenu = async (
}
};
+const readRedditFromPage = async (tabId: number, frameId: number | null, pageUrl: string) => {
+ const requestId = crypto.randomUUID();
+ const result = await new Promise<unknown>((resolve, reject) => {
+ const timeout = setTimeout(() => {
+ pendingRedditReads.delete(requestId);
+ reject(new Error(t("captureTimeout")));
+ }, 12_000);
+ pendingRedditReads.set(requestId, (value) => {
+ clearTimeout(timeout);
+ resolve(value);
+ });
+ const target = scriptTarget(tabId, frameId);
+ const inject = async () => {
+ await chrome.scripting.executeScript({
+ target,
+ func: (value: unknown) => {
+ (globalThis as { __edgeeverRedditClipPayload?: unknown }).__edgeeverRedditClipPayload = value;
+ },
+ args: [{ requestId, pageUrl }],
+ });
+ await chrome.scripting.executeScript({ target, files: ["assets/capture-reddit.js"] });
+ };
+ void inject().catch((error: unknown) => {
+ clearTimeout(timeout);
+ pendingRedditReads.delete(requestId);
+ reject(new Error(describeCaptureError(error)));
+ });
+ });
+ return result && typeof result === "object" ? result as Record<string, unknown> : {};
+};
+
+const saveRedditFromMenu = async (
+ info: { pageUrl?: string; linkUrl?: 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("redditNotFound"));
+ const result = await readRedditFromPage(tabId, frameId, info.linkUrl || tab?.url || info.pageUrl || "");
+ if (result.ok === false && result.reason === "needs-listener") {
+ await chrome.scripting.executeScript({ target: { tabId }, files: ["assets/reddit-target.js"] });
+ await showFeedback(tabId, frameId, t("redditRightClickAgain"), "success");
+ return;
+ }
+ const id = typeof result.id === "string" ? result.id : "";
+ const post = redditPostFromApi(result.api, id) ?? redditPostFromDom(result.dom, id);
+ if (!post) throw new Error(t("redditNotFound"));
+ await showFeedback(tabId, frameId, t("savingReddit"), "success");
+ const images = [];
+ for (const image of post.images) {
+ const stored = await readTweetImage(tabId, frameId, image.url, image.alt || post.title);
+ if (stored) images.push({ ...stored, url: image.url });
+ }
+ await saveCapturedRedditPost(imageNoteClient(settings), post, {
+ notebookId: settings.notebookId,
+ sourceLabel: t("sourceLabel"),
+ capturedAtLabel: t("capturedAtLabel"),
+ timeLabel: t("tweetTimeLabel"),
+ authorLabel: t("redditAuthorLabel"),
+ communityLabel: t("redditCommunityLabel"),
+ linkLabel: t("redditLinkLabel"),
+ capturedAt: new Date().toISOString(),
+ images,
+ });
+ await showFeedback(tabId, frameId, t("redditSaved"), "success");
+ } catch (error) {
+ const message = error instanceof Error && error.message === t("redditNotFound")
+ ? error.message
+ : error instanceof Error && error.message === "no-notebook"
+ ? t("noAvailableNotebooks")
+ : describeImageError(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>;
@@ -1193,9 +1288,9 @@ const registerClipMenus = () => {
// 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, 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 on install/update so a previous
+ // the rest of a Zhihu answer or article or Reddit post saves that item.
+ // The Reddit title-link command is limited to Reddit post permalinks, so
+ // linked photos keep the image command. Recreate from scratch so a previous
// registration cannot keep an overlapping item. Context menus persist across
// service worker and event page restarts; removing them at module startup can
// leave the browser with no menus while the background is waking up.
@@ -1254,11 +1349,28 @@ const createClipMenus = () => {
}, () => {
void chrome.runtime.lastError;
});
+ chrome.contextMenus.create({
+ id: REDDIT_MENU_ID,
+ title: t("saveRedditToEdgeEver"),
+ contexts: ["page", "video"],
+ documentUrlPatterns: REDDIT_DOCUMENT_PATTERNS,
+ }, () => {
+ void chrome.runtime.lastError;
+ });
+ chrome.contextMenus.create({
+ id: REDDIT_LINK_MENU_ID,
+ title: t("saveRedditToEdgeEver"),
+ contexts: ["link"],
+ documentUrlPatterns: REDDIT_DOCUMENT_PATTERNS,
+ targetUrlPatterns: REDDIT_DOCUMENT_PATTERNS.map((pattern) => pattern.replace("/*", "/*/comments/*")),
+ }, () => {
+ void chrome.runtime.lastError;
+ });
};
chrome.runtime.onInstalled.addListener(registerClipMenus);
-chrome.contextMenus.onClicked.addListener((info: { menuItemId?: string | number; srcUrl?: string; pageUrl?: string; frameId?: number; selectionText?: string }, tab?: { id?: number; url?: string; title?: string }) => {
+chrome.contextMenus.onClicked.addListener((info: { menuItemId?: string | number; srcUrl?: string; pageUrl?: string; linkUrl?: string; frameId?: number; selectionText?: string }, tab?: { id?: number; url?: string; title?: string }) => {
if (info.menuItemId === SELECTION_MENU_ID) {
void enqueueClip(() => saveSelectionFromMenu(info, tab));
return;
@@ -1281,6 +1393,10 @@ chrome.contextMenus.onClicked.addListener((info: { menuItemId?: string | number;
}
if (info.menuItemId === ZHIHU_MENU_ID) {
void enqueueClip(() => saveZhihuFromMenu(info, tab));
+ return;
+ }
+ if (info.menuItemId === REDDIT_MENU_ID || info.menuItemId === REDDIT_LINK_MENU_ID) {
+ void enqueueClip(() => saveRedditFromMenu(info, tab));
}
});
@@ -1338,6 +1454,12 @@ chrome.runtime.onMessage.addListener((message: { type?: string; page?: CapturedP
return false;
}
+ if (message.type === "pageRedditRead" && message.requestId) {
+ pendingRedditReads.get(message.requestId)?.(message.result);
+ pendingRedditReads.delete(message.requestId);
+ return false;
+ }
+
if (message.type === "activateTweetTarget") {
void (async () => {
const stored = await chrome.storage.session.get(PENDING_TWEET_KEY);
diff --git a/apps/extension/src/capture-reddit.ts b/apps/extension/src/capture-reddit.ts
new file mode 100644
index 00000000..32749cb4
--- /dev/null
+++ b/apps/extension/src/capture-reddit.ts
@@ -0,0 +1,76 @@
+// On-demand Reddit reader. Fetches the selected post's own JSON when Reddit
+// allows it, then falls back to the selected post's DOM. Never reads comments.
+(() => {
+ const root = globalThis as typeof globalThis & {
+ __edgeeverRedditTarget?: boolean;
+ __edgeeverRedditClipPayload?: { requestId?: string; pageUrl?: string };
+ };
+ const payload = root.__edgeeverRedditClipPayload;
+ delete root.__edgeeverRedditClipPayload;
+ if (!payload || typeof payload.requestId !== "string") return;
+ const finish = (result: Record<string, unknown>) => {
+ void chrome.runtime.sendMessage({ type: "pageRedditRead", requestId: payload.requestId, result });
+ };
+ const idFromUrl = (value: string) => {
+ try { return new URL(value, location.href).pathname.match(/\/comments\/([a-z0-9]+)(?=\/|$)/i)?.[1]?.toLowerCase() ?? ""; }
+ catch { return ""; }
+ };
+ const postId = (node: Element) => {
+ const direct = node.getAttribute("id")?.match(/^t3_([a-z0-9]+)$/i)?.[1]
+ || node.getAttribute("data-fullname")?.match(/^t3_([a-z0-9]+)$/i)?.[1]
+ || node.getAttribute("post-id")?.replace(/^t3_/, "");
+ if (direct && /^[a-z0-9]+$/i.test(direct)) return direct.toLowerCase();
+ return idFromUrl(node.getAttribute("permalink") || node.querySelector('a[href*="/comments/"]')?.getAttribute("href") || "");
+ };
+ const clean = (value: string | null | undefined) => (value || "").replace(/\u00a0/g, " ").trim();
+ const selected = document.querySelector("[data-edgeever-reddit-target='1']");
+ const currentId = idFromUrl(payload.pageUrl || location.href);
+ const post = (selected && (!currentId || postId(selected) === currentId) ? selected : null)
+ || [...document.querySelectorAll("shreddit-post, article[data-testid='post-container'], [data-testid='post-container'], .thing.link[data-fullname]")]
+ .find((node) => currentId && postId(node) === currentId);
+ const id = post ? postId(post) : currentId;
+ if (!id || (!post && !currentId)) {
+ finish({ ok: false, reason: root.__edgeeverRedditTarget ? "not-found" : "needs-listener" });
+ return;
+ }
+ const scope = post || document;
+ const ownText = (selector: string) => clean(scope.querySelector(selector)?.textContent);
+ const title = clean(post?.getAttribute("post-title")) || ownText('[slot="title"], h1, h2, h3, [data-testid="post-title"]');
+ const author = clean(post?.getAttribute("author")) || ownText('[data-testid="post_author_link"], a[href*="/user/"]');
+ const subreddit = clean(post?.getAttribute("subreddit-prefixed-name")) || ownText('a[href^="/r/"], [data-testid="subreddit-name"]');
+ const bodyNode = scope.querySelector('[slot="text-body"], [data-testid="post-content"], .md-container, .usertext-body .md, [data-click-id="text"]');
+ const body = clean(bodyNode?.textContent);
+ const link = clean(post?.getAttribute("content-href")) || clean(scope.querySelector('a[data-testid="outbound-link"]')?.getAttribute("href"));
+ const timeNode = scope.querySelector("time[datetime], faceplate-timeago[ts]");
+ const datetime = clean(timeNode?.getAttribute("datetime") || timeNode?.getAttribute("ts"));
+ const images: Array<{ url: string; alt: string }> = [];
+ for (const img of scope.querySelectorAll('img[src], img[data-src]')) {
+ if (img.closest('shreddit-comment, [data-testid="comment"], .comment')) continue;
+ const src = img.getAttribute("src") || img.getAttribute("data-src") || "";
+ try {
+ const url = new URL(src, location.href);
+ if (url.protocol !== "https:" || !/(^|\.)(redd\.it|redditmedia\.com)$/.test(url.hostname)) continue;
+ if (/avatar|icon|emoji|award|preview\.reddit/i.test(url.pathname) && !/i\.redd\.it/.test(url.hostname)) continue;
+ if (images.some((image) => image.url === url.href)) continue;
+ images.push({ url: url.href, alt: clean(img.getAttribute("alt")) });
+ if (images.length >= 20) break;
+ } catch { /* Ignore invalid image addresses. */ }
+ }
+ const dom = { id, title, author, subreddit, body, externalUrl: link, datetime, images };
+ void (async () => {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 8000);
+ try {
+ const response = await fetch(`/comments/${id}/.json?raw_json=1&limit=0`, {
+ credentials: "include", headers: { accept: "application/json" }, signal: controller.signal,
+ });
+ if (response.ok) {
+ const data = await response.json();
+ finish({ ok: true, id, api: data, dom });
+ return;
+ }
+ } catch { /* Reddit may rate-limit or disable JSON on a page. */ }
+ finally { clearTimeout(timeout); }
+ finish({ ok: true, id, api: null, dom });
+ })();
+})();
diff --git a/apps/extension/src/reddit-clip.ts b/apps/extension/src/reddit-clip.ts
new file mode 100644
index 00000000..ea551858
--- /dev/null
+++ b/apps/extension/src/reddit-clip.ts
@@ -0,0 +1,172 @@
+import type { ImageNoteClient } from "./image-clip";
+
+export type RedditPost = {
+ id: string;
+ url: string;
+ title: string;
+ author: string;
+ subreddit: string;
+ body: string;
+ externalUrl: string;
+ datetime: string;
+ images: Array<{ url: string; alt: string }>;
+};
+
+const redditHosts = new Set(["reddit.com", "www.reddit.com", "old.reddit.com", "new.reddit.com", "sh.reddit.com"]);
+const clean = (value: unknown) => typeof value === "string" ? value.trim() : "";
+const imageUrl = (value: unknown) => {
+ const raw = clean(value).replace(/&amp;/g, "&");
+ try {
+ const url = new URL(raw);
+ return url.protocol === "https:" && /(^|\.)redd\.it$|(^|\.)redditmedia\.com$/.test(url.hostname) ? url.href : "";
+ } catch { return ""; }
+};
+const externalUrl = (value: unknown) => {
+ try {
+ const url = new URL(clean(value));
+ return url.protocol === "https:" || url.protocol === "http:" ? url.href : "";
+ } catch { return ""; }
+};
+const isInternalRedditUrl = (value: string) => {
+ try { return redditHosts.has(new URL(value).hostname.toLowerCase()); }
+ catch { return false; }
+};
+const label = (value: string) => value.replace(/[\r\n]+/g, " ").replace(/\\/g, "\\\\").replace(/\[/g, "\\[").replace(/\]/g, "\\]");
+const destination = (value: string) => value.replace(/ /g, "%20").replace(/\(/g, "%28").replace(/\)/g, "%29");
+
+export const redditPostIdFromUrl = (value: string) => {
+ try {
+ const url = new URL(value);
+ if (!redditHosts.has(url.hostname.toLowerCase())) return "";
+ return url.pathname.match(/\/comments\/([a-z0-9]+)(?=\/|$)/i)?.[1]?.toLowerCase() ?? "";
+ } catch { return ""; }
+};
+
+export const redditCanonicalUrl = (id: string, subreddit = "") => {
+ if (!/^[a-z0-9]+$/i.test(id)) return "";
+ const community = /^r\/[A-Za-z0-9_]+$/.test(subreddit) ? `/${subreddit}` : "";
+ return `https://www.reddit.com${community}/comments/${id.toLowerCase()}/`;
+};
+
+export const redditPostFromApi = (raw: unknown, expectedId: string): RedditPost | null => {
+ const listing = Array.isArray(raw) ? raw[0] : null;
+ const children = listing && typeof listing === "object"
+ ? (listing as { data?: { children?: unknown } }).data?.children : null;
+ const first = Array.isArray(children) ? children[0] : null;
+ const data = first && typeof first === "object" ? (first as { data?: Record<string, unknown> }).data : null;
+ if (!data || clean(data.id).toLowerCase() !== expectedId.toLowerCase()) return null;
+ const id = expectedId.toLowerCase();
+ const subreddit = clean(data.subreddit) ? `r/${clean(data.subreddit)}` : "";
+ const canonical = redditCanonicalUrl(id, subreddit);
+ const images: RedditPost["images"] = [];
+ const addImage = (url: unknown, alt = "") => {
+ const normalized = imageUrl(url);
+ if (normalized && !images.some((image) => image.url === normalized) && images.length < 20) {
+ images.push({ url: normalized, alt });
+ }
+ };
+ const gallery = data.gallery_data && typeof data.gallery_data === "object"
+ ? data.gallery_data as { items?: Array<{ media_id?: string; caption?: string }> } : null;
+ const metadata = data.media_metadata && typeof data.media_metadata === "object"
+ ? data.media_metadata as Record<string, { s?: { u?: string } }> : {};
+ for (const item of Array.isArray(gallery?.items) ? gallery.items : []) addImage(metadata[item.media_id ?? ""]?.s?.u, clean(item.caption));
+ if (images.length === 0) addImage(data.url_overridden_by_dest);
+ if (images.length === 0) {
+ const preview = data.preview && typeof data.preview === "object"
+ ? data.preview as { images?: Array<{ source?: { url?: string } }> } : null;
+ addImage(preview?.images?.[0]?.source?.url);
+ }
+ const created = typeof data.created_utc === "number" && Number.isFinite(data.created_utc)
+ && data.created_utc > 0 && data.created_utc < 8_640_000_000_000
+ ? new Date(data.created_utc * 1000).toISOString() : "";
+ const outgoing = externalUrl(data.url_overridden_by_dest);
+ return {
+ id, url: canonical, title: clean(data.title), author: clean(data.author), subreddit,
+ body: clean(data.selftext),
+ externalUrl: outgoing && !isInternalRedditUrl(outgoing) && !images.some((image) => image.url === outgoing) ? outgoing : "",
+ datetime: created, images,
+ };
+};
+
+export const redditPostFromDom = (raw: unknown, expectedId: string): RedditPost | null => {
+ if (!raw || typeof raw !== "object") return null;
+ const value = raw as Record<string, unknown>;
+ if (clean(value.id).toLowerCase() !== expectedId.toLowerCase()) return null;
+ const subreddit = clean(value.subreddit).match(/^r\/[A-Za-z0-9_]+$/)?.[0] ?? "";
+ const images: RedditPost["images"] = [];
+ if (Array.isArray(value.images)) {
+ for (const item of value.images.slice(0, 20)) {
+ const image = item && typeof item === "object" ? item as Record<string, unknown> : {};
+ const url = imageUrl(image.url);
+ if (url && !images.some((stored) => stored.url === url)) images.push({ url, alt: clean(image.alt) });
+ }
+ }
+ const datetime = clean(value.datetime);
+ const outgoing = externalUrl(value.externalUrl);
+ const post: RedditPost = {
+ id: expectedId.toLowerCase(), url: redditCanonicalUrl(expectedId, subreddit),
+ title: clean(value.title), author: clean(value.author).replace(/^u\//, ""), subreddit,
+ body: clean(value.body),
+ externalUrl: outgoing && !isInternalRedditUrl(outgoing) ? outgoing : "",
+ datetime: datetime && !Number.isNaN(Date.parse(datetime)) ? new Date(datetime).toISOString() : "",
+ images,
+ };
+ return post.title ? post : null;
+};
+
+export const redditPostMarkdown = (post: RedditPost, input: {
+ sourceLabel: string; capturedAtLabel: string; timeLabel: string; authorLabel: string;
+ communityLabel: string; linkLabel: string; capturedAt: string;
+ uploaded?: Array<{ url: string; resourceId: string }>;
+}) => {
+ const parts = [`# ${post.title.replace(/[\r\n]+/g, " ").trim()}`];
+ if (post.subreddit) parts.push(`${input.communityLabel}: ${post.subreddit}`);
+ if (post.author) parts.push(`${input.authorLabel}: u/${post.author.replace(/^u\//, "")}`);
+ if (post.body) parts.push(post.body);
+ if (post.externalUrl) parts.push(`${input.linkLabel}: [${label(post.externalUrl)}](${destination(post.externalUrl)})`);
+ if (post.images.length) parts.push(post.images.map((image) => {
+ const resource = input.uploaded?.find((item) => item.url === image.url)?.resourceId;
+ const url = resource ? `/api/v1/resources/${encodeURIComponent(resource)}/blob` : image.url;
+ return `![${label(image.alt || post.title)}](${destination(url)})`;
+ }).join("\n\n"));
+ parts.push(`${input.sourceLabel}: [${label(post.url)}](${destination(post.url)})`);
+ if (post.datetime) parts.push(`${input.timeLabel}: ${post.datetime}`);
+ parts.push(`${input.capturedAtLabel}: ${input.capturedAt}`);
+ return parts.join("\n\n");
+};
+
+export const saveCapturedRedditPost = async (
+ client: ImageNoteClient,
+ post: RedditPost,
+ input: { notebookId: string; sourceLabel: string; capturedAtLabel: string; timeLabel: string; authorLabel: string;
+ communityLabel: string; linkLabel: string; capturedAt: string;
+ images: Array<{ url: string; bytes: Uint8Array; mimeType: string; filename: string; alt: string }> },
+) => {
+ const notebookId = input.notebookId || (await client.listNotebooks()).notebooks[0]?.id;
+ if (!notebookId) throw new Error("no-notebook");
+ const created = await client.createMemo({
+ notebookId, title: post.title || `${post.subreddit} post`,
+ contentMarkdown: redditPostMarkdown(post, input), tags: ["web-clip"],
+ });
+ const memoId = created.memo.id;
+ if (!memoId) throw new Error("create-missing-id");
+ const uploaded: Array<{ url: string; resourceId: string }> = [];
+ for (const image of input.images) {
+ try {
+ const resource = await client.uploadImage(memoId, image);
+ if (resource.id) uploaded.push({ url: image.url, resourceId: resource.id });
+ } catch { /* Keep the remote image in the saved note. */ }
+ }
+ if (uploaded.length) {
+ try {
+ const session = await client.createEditSession(memoId);
+ await client.saveMemo(memoId, {
+ editSessionId: session.editSession.id,
+ expectedRevision: session.editSession.baseRevision,
+ expectedContentHash: session.editSession.baseContentHash,
+ contentMarkdown: redditPostMarkdown(post, { ...input, uploaded }),
+ });
+ } catch { /* The first revision remains useful. */ }
+ }
+ return { memoId, resourceIds: uploaded.map((item) => item.resourceId) };
+};
diff --git a/apps/extension/src/reddit-target.ts b/apps/extension/src/reddit-target.ts
new file mode 100644
index 00000000..72011ff7
--- /dev/null
+++ b/apps/extension/src/reddit-target.ts
@@ -0,0 +1,29 @@
+// Remembers the exact Reddit post under the pointer. The reader runs only after
+// the user chooses the context menu command. This classic content script has no imports.
+(() => {
+ const root = globalThis as typeof globalThis & { __edgeeverRedditTarget?: boolean };
+ if (root.__edgeeverRedditTarget) return;
+ root.__edgeeverRedditTarget = true;
+
+ const idFromUrl = (value: string) => {
+ try {
+ return new URL(value, location.href).pathname.match(/\/comments\/([a-z0-9]+)(?=\/|$)/i)?.[1]?.toLowerCase() ?? "";
+ } catch { return ""; }
+ };
+ const postId = (node: Element) => {
+ const direct = node.getAttribute("id")?.match(/^t3_([a-z0-9]+)$/i)?.[1]
+ || node.getAttribute("data-fullname")?.match(/^t3_([a-z0-9]+)$/i)?.[1]
+ || node.getAttribute("post-id")?.replace(/^t3_/, "");
+ if (direct && /^[a-z0-9]+$/i.test(direct)) return direct.toLowerCase();
+ const permalink = node.getAttribute("permalink") || node.querySelector('a[href*="/comments/"]')?.getAttribute("href") || "";
+ return idFromUrl(permalink);
+ };
+
+ document.addEventListener("contextmenu", (event) => {
+ document.querySelectorAll("[data-edgeever-reddit-target]").forEach((node) => node.removeAttribute("data-edgeever-reddit-target"));
+ const target = event.target instanceof Element ? event.target
+ : event.target instanceof Node ? event.target.parentElement : null;
+ const post = target?.closest("shreddit-post, article[data-testid='post-container'], [data-testid='post-container'], .thing.link[data-fullname]");
+ if (post && postId(post)) post.setAttribute("data-edgeever-reddit-target", "1");
+ }, true);
+})();
diff --git a/apps/extension/vite.config.ts b/apps/extension/vite.config.ts
index 1ce861fa..1d9479d4 100644
--- a/apps/extension/vite.config.ts
+++ b/apps/extension/vite.config.ts
@@ -36,11 +36,13 @@ export default defineConfig({
"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)),
+ "capture-reddit": fileURLToPath(new URL("./src/capture-reddit.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)),
+ "reddit-target": fileURLToPath(new URL("./src/reddit-target.ts", import.meta.url)),
"zhihu-save": fileURLToPath(new URL("./zhihu-save.html", import.meta.url)),
},
output: {