最近文档¶
概述¶
Windows 和 macOS 分别通过 JumpList 或程序坞菜单提供访问应用程序打开的最近文档列表的功能。
JumpList:

应用程序程序坞菜单:

示例¶
管理最近文档¶
```fiddle docs/fiddles/features/recent-documents const { app, BrowserWindow } = require('electron/main') const fs = require('node:fs') const path = require('node:path')
function createWindow () { const win = new BrowserWindow({ width: 800, height: 600 })
win.loadFile('index.html') }
const fileName = 'recently-used.md' fs.writeFile(fileName, 'Lorem Ipsum', () => { app.addRecentDocument(path.join(__dirname, fileName)) })
app.whenReady().then(createWindow)
app.on('window-all-closed', () => { app.clearRecentDocuments() if (process.platform !== 'darwin') { app.quit() } })
app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow() } })
#### 添加最近文档 {#adding-a-recent-document}
要将文件添加到最近文档,请使用
[app.addRecentDocument][addrecentdocument] API。
启动 Electron 应用程序后,右键单击应用程序图标。
在本指南中,该文件是位于项目根目录下的 Markdown 文件。
你应该会在最近文件列表中看到 `recently-used.md`:

#### 清除最近文档列表 {#clearing-the-list-of-recent-documents}
要清除最近文档列表,请使用
[app.clearRecentDocuments][clearrecentdocuments] API。
在本指南中,当所有窗口关闭后,文档列表会被清除。
#### 访问最近文档列表 {#accessing-the-list-of-recent-documents}
要访问最近文档列表,请使用
[app.getRecentDocuments][getrecentdocuments] API。
## 附加信息 {#additional-information}
### Windows 注意事项 {#windows-notes}
要在 Windows 上使用此功能,你的应用程序必须注册为文档文件类型的处理程序,否则即使已添加,文件也不会出现在 JumpList 中。有关注册应用程序的所有信息,请参阅 [应用程序注册][app-registration]。
当用户从 JumpList 中单击文件时,将启动你的应用程序的新实例,并将该文件的路径作为命令行参数添加。
### macOS 注意事项 {#macos-notes}
#### 将最近文档列表添加到应用程序菜单 {#add-the-recent-documents-list-to-the-application-menu}
你可以通过在菜单模板中添加以下代码片段,来添加用于访问和清除最近文档的菜单项:
```json
{
"submenu":[
{
"label":"Open Recent",
"role":"recentdocuments",
"submenu":[
{
"label":"Clear Recent",
"role":"clearrecentdocuments"
}
]
}
]
}
请确保应用程序菜单在 'ready'
事件之后添加,而不是之前,否则菜单项将被禁用:
const { app, Menu } = require('electron')
const template = [
// Menu template here
]
const menu = Menu.buildFromTemplate(template)
app.whenReady().then(() => {
Menu.setApplicationMenu(menu)
})

当从最近文档菜单请求文件时,app 模块会为其发出 open-file 事件。
本页原文 Markdown:在 AtomGit 查看·内容源自开源项目 el/electron