运用 Electron 翻开外部链接或文件管理器
此系列文章的运用示例已宣布于 GitHub: electron-api-demos-Zh_CN. 能够 Clone 或下载后运转检察. 迎接 Star .
Electron 中的 shell
模块许可您接见某些当地元素, 如文件管理器和默许 Web 浏览器.
此模块在主历程和渲染器历程中都能够事情.
在浏览器中检察 完全 API 文档.
在文件管理器中翻开途径
支撑: Win, macOS, Linux | 历程: Both
当前示例运用 shell
模块在特定位置翻开体系文件管理器.
单击示例按钮将在根目录中翻开文件管理器.
渲染器历程
const shell = require('electron').shell
const os = require('os')
const fileManagerBtn = document.getElementById('open-file-manager')
fileManagerBtn.addEventListener('click', function (event) {
shell.showItemInFolder(os.homedir())
})
翻开外部链接
支撑: Win, macOS, Linux | 历程: Both
假如您不愿望在当前运用程序中翻开网站链接, 能够运用 shell
模块在外部翻开. 当点击链接以后将在用户的默许浏览器中翻开.
当点击示例按钮时, 将在您的浏览器中翻开 Electron 的网站.
渲染器历程
const shell = require('electron').shell
const exLinksBtn = document.getElementById('open-ex-links')
exLinksBtn.addEventListener('click', function (event) {
shell.openExternal('http://electron.atom.io')
})
高等技能
在外部翻开一切出站链接.
您能够须要翻开运用外部的一切 http
和 https
链接. 为此, 查询文档并轮回遍历每一个链接并增加一个监听器. 此运用程序运用位于 assets/ex-links.js
下面的代码.
渲染器历程
const shell = require('electron').shell
const links = document.querySelectorAll('a[href]')
Array.prototype.forEach.call(links, function (link) {
const url = link.getAttribute('href')
if (url.indexOf('http') === 0) {
link.addEventListener('click', function (e) {
e.preventDefault()
shell.openExternal(url)
})
}
})
假如这边文章对您有协助, 感谢 下方点赞 或 Star GitHub: electron-api-demos-Zh_CN 支撑, 感谢.