# 我创建了一个书签脚本，用于生成论坛帖子目录

**URL:** <https://meta.discourse.org/t/i-created-a-bookmarklet-to-create-the-table-of-content-for-forum-posts/270961>\
**Category:** Development\
**Created:** [2023 年7 月 8 日 02:33 UTC](https://meta.discourse.org/t/i-created-a-bookmarklet-to-create-the-table-of-content-for-forum-posts/270961 "2023-07-08T02:33:56Z")\
**Posts on this page:** 1\
**Showing post:** 1

<div class="post-metadata">

作者： ![ShunS](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/shuns/32/314884_2.png) [@ShunS](https://meta.discourse.org/u/ShunS)\
发布日期： [2023 年7 月 8 日 02:33 UTC](https://meta.discourse.org/t/i-created-a-bookmarklet-to-create-the-table-of-content-for-forum-posts/270961/1 "2023-07-08T02:33:56Z")

</div>

> **目录：**
>
> - [摘要](https://meta.discourse.org/t/i-created-a-bookmarklet-to-create-the-table-of-content-of-forum-posts/270961#summary-1)  
> - [如何使用](https://meta.discourse.org/t/i-created-a-bookmarklet-to-create-the-table-of-content-of-forum-posts/270961#how-to-use-2)  
> &nbsp;&nbsp;&nbsp;&nbsp;[安装](https://meta.discourse.org/t/i-created-a-bookmarklet-to-create-the-table-of-content-of-forum-posts/270961#installation-3)  
> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[代码功能](https://meta.discourse.org/t/i-created-a-bookmarklet-to-create-the-table-of-content-of-forum-posts/270961#what-the-code-does-4)  
> - [生成目录](https://meta.discourse.org/t/i-created-a-bookmarklet-to-create-the-table-of-content-of-forum-posts/270961#generating-toc-5)  
> &nbsp;&nbsp;&nbsp;&nbsp;[使用目录](https://meta.discourse.org/t/i-created-a-bookmarklet-to-create-the-table-of-content-of-forum-posts/270961#using-toc-6)  
> - [技术说明（面向技术人员）](https://meta.discourse.org/t/i-created-a-bookmarklet-to-create-the-table-of-content-of-forum-posts/270961#technical-notes-for-technical-people-7)  
> - [截图](https://meta.discourse.org/t/i-created-a-bookmarklet-to-create-the-table-of-content-of-forum-posts/270961#screenshots-8)

我创建了一个书签小工具，用于生成可折叠的目录（ToC），就像上面显示的那样。  
希望它能帮助那些喜欢写长文的社区成员！

# 摘要

我有时会写很长的帖子/主题，需要一个目录来方便阅读。  
我发现了一些现有的工具，例如 [https://meta.discourse.org/t/discotoc-automatic-table-of-contents/111143，但我需要一个只为我自己使用的工具，不需要在整个社区安装。](https://meta.discourse.org/t/discotoc-automatic-table-of-contents/111143%EF%BC%8C%E4%BD%86%E6%88%91%E9%9C%80%E8%A6%81%E4%B8%80%E4%B8%AA%E5%8F%AA%E4%B8%BA%E6%88%91%E8%87%AA%E5%B7%B1%E4%BD%BF%E7%94%A8%E7%9A%84%E5%B7%A5%E5%85%B7%EF%BC%8C%E4%B8%8D%E9%9C%80%E8%A6%81%E5%9C%A8%E6%95%B4%E4%B8%AA%E7%A4%BE%E5%8C%BA%E5%AE%89%E8%A3%85%E3%80%82)

发布结构化的帖子后，点击书签小工具，目录就会被复制到剪贴板。编辑帖子，然后将目录粘贴到顶部！

# 如何使用

## 安装

1. 将页面保存为书签。
2. 编辑名称，例如“📋 将论坛目录复制到剪贴板。”
3. 编辑 URL 并粘贴以下代码。如果需要，请自定义代码——请参阅下面的两个“可选”项目。

```javascript
javascript:(function() {
	const copyForumTocToClipboard = function() {
		const urlMatch = window.location.href.match(/\/t\/[^\/]*\/\d+\/?(\d*)/);
		if (!urlMatch) return;

		const postIndex = urlMatch ? urlMatch[1] : 1;
		const anchors = document.querySelectorAll('#post_' + postIndex + ' div.cooked h6 a.anchor,h5 a.anchor,h4 a.anchor,h3 a.anchor,h2 a.anchor,h1 a.anchor');
		if (!anchors) return;

		let toc = '';
		anchors.forEach(anchor => {
			toc +=
				' '.repeat((anchor.parentNode.nodeName[1] - 1) * 4) +
				`<a href="${anchor.href}">${anchor.parentNode.textContent}</a><br>\n`;
		});
		if (!toc) return;

		navigator.clipboard.writeText('<details open><summary>Table of contents: </summary><ul>\n' + toc + '</ul></details>');
	};

	copyForumTocToClipboard();
})();

```

### 代码功能

1. 检查 URL 是否看起来像一个社区帖子：`https://{domain}/t/{title}/{topicID}(/{postIndex})`。
2. 检查帖子中是否包含 🔗 锚点（标题，如 `<h1>` 和 `# `）。
3. 生成目录的 HTML 代码。
4. 将代码复制到剪贴板。

## 生成目录

1. 发布一个带有结构的帖子（HTML `<h1>`, `<h2>`, … 和 Markdown `# `, `## `, …）。Discourse 会为每个标题分配锚点。
2. 确保你的帖子被选中，查看进度条（例如，`1/22`）或 URL（例如，`/1`）。
3. 点击书签栏中的书签小工具。
4. 目录已复制到剪贴板。

## 使用目录

1. 点击铅笔图标编辑帖子。
2. 将代码粘贴到顶部。
3. 检查目录项是否正确显示（已知问题：书签小工具会丢失一些表情符号）。
4. （可选）更改/翻译“目录”。
5. （可选）删除 ` open`，如果你想让目录默认折叠。
6. 点击“保存编辑”。如果你在发布帖子后几分钟内这样做，你的帖子将不会添加“已编辑”的铅笔图标。

# 技术说明（面向技术人员）

- 你也可以将 JavaScript 代码复制并粘贴到开发者控制台中。
  - 我将代码包装在一个函数中，因为 `return;` 在函数外部不起作用。

- `'\u0026nbsp;'.repeat()` 方法在预览主题时看起来有点乱，但在实际帖子中（与使用 `<li></li>` 相比）看起来效果最好（在我看来）。
- 当我测试 `querySelectorAll` 时，不知何故 `h6 a.anchor,h5 a.anchor, ...` 中的第一个项目没有找到。我把 `h6` 放在最前面，因为它可能是最不常用的。
- 如果 Discourse 更改其 UI/DOM，书签小工具可能会停止工作。如果你发现错误，请回复我。

# 截图

作为 [meta.discourse.org](http://meta.discourse.org) 的新用户，我无法添加多张图片，所以我将所有截图合并在一张图片中：

 ![bookmarklet screenshot](https://global.discourse-cdn.com/meta/original/4X/5/9/0/590300bd8da91768e365c38d62049023a7e49120.jpeg)

---

_[View the full topic](https://meta.discourse.org/t/i-created-a-bookmarklet-to-create-the-table-of-content-for-forum-posts/270961)._
