在 BrowserWindow 中呈現檔案
概述
在 macOS 上,您可以為應用程式中的任何視窗設定一個代表的檔案。代表檔案的圖示將會顯示在標題列中,並且當使用者按下 Command-Click
或 Control-Click
時,將會顯示一個帶有檔案路徑的彈出視窗。
注意:上面的螢幕截圖是一個範例,其中使用此功能來指示 Atom 文字編輯器中目前開啟的檔案。
您也可以為視窗設定編輯狀態,以便檔案圖示可以指示此視窗中的文件是否已修改。
要設定視窗的代表檔案,您可以使用 BrowserWindow.setRepresentedFilename 和 BrowserWindow.setDocumentEdited API。
範例
- main.js
- index.html
const { app, BrowserWindow } = require('electron/main')
const os = require('node:os')
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600
})
win.setRepresentedFilename(os.homedir())
win.setDocumentEdited(true)
win.loadFile('index.html')
}
app.whenReady().then(() => {
createWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
<link rel="stylesheet" type="text/css" href="./styles.css">
</head>
<body>
<h1>Hello World!</h1>
<p>
Click on the title with the <pre>Command</pre> or <pre>Control</pre> key pressed.
You should see a popup with the represented file at the top.
</p>
</body>
</body>
</html>
啟動 Electron 應用程式後,按住 Command
或 Control
鍵並點擊標題。您應該會在頂部看到一個帶有代表檔案的彈出視窗。在本指南中,這是目前使用者的主目錄