最近的文件
概览
Windows 和 macOS 分别通过打开跳转列表和dock菜单使应用程序能够快速的访问最近打开的文档列表。
JumpList:
应用 dock 菜单
示例
管理最近的文档
- main.js
- index.html
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()
}
})
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Recent Documents</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body>
<h1>Recent Documents</h1>
<p>
Right click on the app icon to see recent documents.
You should see `recently-used.md` added to the list of recent files
</p>
</body>
</html>
添加最近的文档
To add a file to recent documents, use the app.addRecentDocument API.
启动 Electron 应用程序后,右键点击应用程序图标。 在本指南中,本项是位于项目根目录下的 Markdown 文件: 您应该可以看到添加到最近文件列表中的 recently-used.md
:
清除最近文档列表
To clear the list of recent documents, use the app.clearRecentDocuments API. 在此指南中,一旦所有窗口都关闭,文件列表就会被清除。
Accessing the list of recent documents
To access the list of recent documents, use the app.getRecentDocuments API.
更多信息
Windows 注意事项
若要在 Windows 上使用此功能,您的应用程序必须注册为这类文件的处理程序。 否则,文件将不会在跳转列表中出现。 You can find everything on registering your application in Application Registration.
当用户点击“跳转列表”上的一个文件时,系统会启动一个新的应用程序的实例 ,而文件的路径将作为一个命令行参数被传入这个实例。
macOS 注意事项
将"最近文档列表"添加到应用程序菜单
您可以添加菜单项以访问和清除最近的文档,方法是在菜单模板中添加以下代码片段:
{
"submenu":[
{
"label":"Open Recent",
"role":"recentdocuments",
"submenu":[
{
"label":"Clear Recent",
"role":"clearrecentdocuments"
}
]
}
]
}
Make sure the application menu is added after the 'ready'
event and not before, or the menu item will be disabled:
const { app, Menu } = require('electron')
const template = [
// 这里是菜单模版
]
const menu = Menu.buildFromTemplate(template)
app.whenReady().then(() => {
Menu.setApplicationMenu(menu)
})
从 "最近文档" 菜单中请求文件时, 将为其发出 app
模块的 open-file
事件。