跳转至

最近使用的文档

概述

Windows 和 macOS 分别通过 JumpList(跳转列表)或 Dock 菜单提供对应用程序最近打开的文档列表的访问。

JumpList:

JumpList 最近文件

应用程序 Dock 菜单:

macOS Dock 菜单

示例

管理最近使用的文档

```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`:

![最近使用的文档](https://raw.atomgit.com/GitHub_Trending/el/electron/raw/9ea8e7da48401110ddebcc469ddd2312f3e1b021/docs/images/recent-documents.png)

#### 清空最近使用的文档列表 {#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 = [
  // 菜单模板写在这里
]
const menu = Menu.buildFromTemplate(template)

app.whenReady().then(() => {
  Menu.setApplicationMenu(menu)
})

macOS 最近使用的文档菜单项

当从最近使用的文档菜单中请求某个文件时,app 模块会为它发出 open-file 事件。

本页原文 Markdown:在 AtomGit 查看·内容源自开源项目 el/electron