最近文档 (Windows & macOS)

概览

Windows 和 macOS 分别通过打开跳转列表和dock菜单使应用程序能够快速的访问最近打开的文档列表。

JumpList:

跳转列表最近的文件

应用 dock 菜单

macOS Dock 菜单

示例

管理最近的文档

  • index.html
  • main.js
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Recent Documents</title>
  6. <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
  7. </head>
  8. <body>
  9. <h1>Recent Documents</h1>
  10. <p>
  11. Right click on the app icon to see recent documents.
  12. You should see `recently-used.md` added to the list of recent files
  13. </p>
  14. </body>
  15. </html>
  1. const { app, BrowserWindow } = require('electron')
  2. const fs = require('fs')
  3. const path = require('path')
  4. function createWindow () {
  5. const win = new BrowserWindow({
  6. width: 800,
  7. height: 600
  8. })
  9. win.loadFile('index.html')
  10. }
  11. const fileName = 'recently-used.md'
  12. fs.writeFile(fileName, 'Lorem Ipsum', () => {
  13. app.addRecentDocument(path.join(__dirname, fileName))
  14. })
  15. app.whenReady().then(createWindow)
  16. app.on('window-all-closed', () => {
  17. app.clearRecentDocuments()
  18. if (process.platform !== 'darwin') {
  19. app.quit()
  20. }
  21. })
  22. app.on('activate', () => {
  23. if (BrowserWindow.getAllWindows().length === 0) {
  24. createWindow()
  25. }
  26. })

Open in Fiddle

添加最近的文档

若要增加一个文件到最近文件列表,你可以使用app.addRecentDocument API.

启动 Electron 应用程序后,右键点击应用程序图标。 在本指南中,本项是位于项目根目录下的 Markdown 文件: 您应该可以看到添加到最近文件列表中的 recently-used.md

最近的文档

清除最近文档列表

若要清空最近文件列表,你可以使用app.clearRecentDocuments API. 在此指南中,一旦所有窗口都关闭,文件列表就会被清除。

Additional information

Windows 注意事项

若要在 Windows 上使用此功能,您的应用程序必须注册为这类文件的处理程序。 否则,文件将不会在跳转列表中出现。 你可以在 Application Registration.aspx) 里找到所有关于注册事宜的说明。

当用户点击“跳转列表”上的一个文件时,系统会启动一个新的应用程序的实例 ,而文件的路径将作为一个命令行参数被传入这个实例。

macOS 注意事项

将”最近文档列表”添加到应用程序菜单

您可以添加菜单项以访问和清除最近的文档,方法是在菜单模板中添加以下代码片段:

  1. {
  2. "submenu":[
  3. {
  4. "label":"Open Recent",
  5. "role":"recentdocuments",
  6. "submenu":[
  7. {
  8. "label":"Clear Recent",
  9. "role":"clearrecentdocuments"
  10. }
  11. ]
  12. }
  13. ]
  14. }

请确保在 ‘ready’事件后添加应用菜单而不是之前,否则菜单项将被禁用:

  1. const { app, Menu } = require('electron')
  2. const template = [
  3. // 这里是菜单模版
  4. ]
  5. const menu = Menu.buildFromTemplate(template)
  6. app.whenReady().then(() => {
  7. Menu.setApplicationMenu(menu)
  8. })

macOS 最近文档菜单项

从 “最近文档” 菜单中请求文件时, 将为其发出 app 模块的 open-file 事件。