最近的文件
概觀
Windows 和 macOS 分別透過 JumpList 或 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>
新增最近的文件
若要將檔案新增至最近的文件,請使用 app.addRecentDocument API。
啟動 Electron 應用程式後,按一下應用程式圖示。在本指南中,該項目是一個位於專案根目錄的 Markdown 檔案。您應該會看到 recently-used.md
已新增至最近檔案清單中
清除最近的文件清單
若要清除最近的文件清單,請使用 app.clearRecentDocuments API。在本指南中,一旦所有視窗都已關閉,就會清除文件清單。
其他資訊
Windows 說明
若要在 Windows 上使用此功能,您的應用程式必須註冊為該文件類型的處理常式,否則即使您已新增該檔案,該檔案也不會出現在 JumpList 中。您可以在應用程式註冊中找到有關註冊應用程式的所有資訊。
當使用者從 JumpList 按一下檔案時,將會使用該檔案的路徑作為命令列引數來啟動應用程式的新執行個體。
macOS 說明
將最近的文件清單新增至應用程式選單
您可以將選單項目新增至選單範本,以存取和清除最近的文件
{
"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
事件。