在浏览器窗口中表示文件
🌐 Representing Files in a BrowserWindow
概述
🌐 Overview
在 macOS 上,你可以为应用中的任何窗口设置一个关联文件。关联文件的图标将显示在标题栏中,当用户Command-Click或Control-Click时,将显示一个文件路径的弹出窗口。
🌐 On macOS, you can set a represented file for any window in your application.
The represented file's icon will be shown in the title bar, and when users
Command-Click or Control-Click, a popup with a path to the file will be
shown.

注意:上面的截图是一个示例,展示了在 Atom 文本编辑器中使用此功能来指示当前打开的文件。
你还可以为窗口设置编辑状态,以便文件图标可以指示该窗口中的文档是否已被修改。
🌐 You can also set the edited state for a window so that the file icon can indicate whether the document in this window has been modified.
要设置窗口所表示的文件,可以使用 BrowserWindow.setRepresentedFilename 和 BrowserWindow.setDocumentEdited API。
🌐 To set the represented file of window, you can use the BrowserWindow.setRepresentedFilename and BrowserWindow.setDocumentEdited APIs.
示例
🌐 Example
- 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 键点击标题。你应该会看到一个弹出窗口,顶部显示相应的文件。在本指南中,这个文件位于当前用户的主目录下:
🌐 After launching the Electron application, click on the title with Command or
Control key pressed. You should see a popup with the represented file at the top.
In this guide, this is the current user's home directory:
