Shell 集成
学习如何通过 Electron 的 `shell` 模块,使用操作系统的默认应用打开外部链接、文件和目录
Shell 集成 是 CoddyKit 上的免费 Electron Desktop App Development 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Electron Desktop App Development 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Electron Desktop App Development 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Intro to Shell Integration
Welcome to Shell Integration! In Electron, your desktop app can interact with the user's operating system (OS) in powerful ways.
This means opening external links, files, or even showing items in the OS file explorer, just like native apps do.
Meet the `shell` Module
Electron provides the built-in shell module to make these OS interactions easy and safe. It's available in both the main and renderer processes.
The shell module lets your app delegate tasks like opening URLs or files to the OS's default applications.
Opening External URLs
The most common use case is opening web links in the user's default browser. You can do this with shell.openExternal(url).
This is crucial for security: instead of rendering external web content inside your app, you hand it off to a trusted browser.
Code: Open an External Link
Here's how you can open an external URL. This code would typically be in your main.js or called from a preload script if triggered by the renderer.
Try running this example:
const { app, shell } = require('electron');
app.whenReady().then(() => {
// In a real app, this would be triggered by a user action.
// For this demo, it opens when the app is ready.
shell.openExternal('https://www.electronjs.org/docs')
.then(() => console.log('Opened Electron docs!'))
.catch(err => console.error('Failed to open URL:', err));
// A real Electron app would also create a BrowserWindow here.
});Opening Local Files & Folders
Need to open a document, image, or even a directory from your app? Use shell.openPath(path).
This function attempts to open the given file or directory with the OS's default application for that file type.
Code: Open a Local File
This example creates a simple text file and then opens it using the OS's default text editor.
Try running this example:
const { app, shell } = require('electron');
const path = require('path');
const fs = require('fs');
app.whenReady().then(() => {
const userDataPath = app.getPath('userData');
const filePath = path.join(userDataPath, 'my-document.txt');
// Create a dummy file for demonstration
fs.writeFileSync(filePath, 'Hello from CoddyKit! This is your document.');
shell.openPath(filePath)
.then(() => console.log(`Opened: ${filePath}`))
.catch(err => console.error(`Failed to open path: ${err}`));
});Showing Items in Explorer/Finder
Sometimes you don't want to open a file, but just show where it is. shell.showItemInFolder(fullPath) does just that.
It reveals the specified file in the user's operating system file manager (e.g., File Explorer on Windows, Finder on macOS), and optionally selects it.
Code: Show Item in Folder
Let's create another file and then show its location to the user.
Try running this example:
const { app, shell } = require('electron');
const path = require('path');
const fs = require('fs');
app.whenReady().then(() => {
const desktopPath = app.getPath('desktop');
const fileToShowPath = path.join(desktopPath, 'coddykit_demo_file.txt');
// Create a dummy file on the desktop
fs.writeFileSync(fileToShowPath, 'Find me!');
shell.showItemInFolder(fileToShowPath);
console.log(`Showing item in folder: ${fileToShowPath}`);
});Security & Best Practices
When using shell methods, especially with user-provided input, always consider security:
- Validate URLs: Before calling
openExternal(), ensure the URL is safe and intended. - Context Isolation: In the renderer process, use a preload script to expose only necessary
shellfunctions securely. - Error Handling: Always include
.catch()for promise-based methods likeopenExternalandopenPath.
Quick Check on Shell
Which shell module method would you use to open a web link in the user's default browser?
Recap: Shell Integration
Great job! You've learned how Electron's shell module helps your app interact with the native OS:
shell.openExternal()for web links.shell.openPath()for local files/folders.shell.showItemInFolder()to reveal items in the file manager.
These methods provide a seamless and secure way to extend your app's functionality to the native environment.
常见问题解答
「Shell 集成」课时是免费的吗?
是的 — 「Shell 集成」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Electron Desktop App Development 课程的其余内容,请升级到 CoddyKit PRO。 Electron Desktop App Development 课程共包含 4 节课。
「Shell 集成」这节课中我会学到什么?
学习如何通过 Electron 的 `shell` 模块,使用操作系统的默认应用打开外部链接、文件和目录 你通过在浏览器中直接运行的动手代码来练习 Electron Desktop App Development,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Electron Desktop App Development 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Electron Desktop App Development 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「Shell 集成」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Electron Desktop App Development 课中编写并运行代码吗?
能。每节 Electron Desktop App Development 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 原生菜单与上下文菜单
- 对话框与通知
- Shell 集成
- 全局快捷键与剪贴板访问