此係列文章的應用示例已發佈於 GitHub: electron-api-demos-Zh_CN. 能夠 Clone 或下載後運行查看. 歡迎 Star .html
使用幾個 Node.js 和 Electron 模塊, 您能夠收集有關用戶系統, 應用程序或屏幕的信息.node
相關文檔的連接位於下面的示例中.git
支持: Win, macOS, Linux | 進程: Bothgithub
主進程的 app
模塊可用於獲取應用程序在用戶計算機上的位置.chrome
在這個示例中, 要從渲染器進程獲取信息, 咱們使用 ipc
模塊向主進程發送一條消息, 來請求應用程序的路徑.shell
查看更多 應用模塊文檔.api
渲染器進程瀏覽器
const ipc = require('electron').ipcRenderer const appInfoBtn = document.getElementById('app-info') appInfoBtn.addEventListener('click', function () { ipc.send('get-app-path') }) ipc.on('got-app-path', function (event, path) { const message = `當前應用程序位於: ${path}` document.getElementById('got-app-info').innerHTML = message })
主進程app
const app = require('electron').app const ipc = require('electron').ipcMain ipc.on('get-app-path', function (event) { event.sender.send('got-app-path', app.getAppPath()) })
支持: Win, macOS, Linux | 進程: Bothelectron
process
模塊內置在 Node.js 中(所以您能夠在主進程和渲染器進程中使用此模塊), 而在 Electron 應用程序中, 此對象還有一些更有用的屬性.
下面的示例將獲取應用程序正在使用的 Electron 版本.
查看更多 進程文檔.
渲染器進程
const versionInfoBtn = document.getElementById('version-info') const electronVersion = process.versions.electron versionInfoBtn.addEventListener('click', function () { const message = `當前應用正在使用的 Electron 版本: ${electronVersion}` document.getElementById('got-version-info').innerHTML = message })
查找 Chromium, Node.js 和 V8 的版本.
Electron 還在 process.versions
對象中包括 Chromium, Node.js 和 V8 的版本. 您能夠經過在 Electron 應用中打開開發人員工具並鍵入 process.versions
來快速查看.
// 返回正在使用的 Chromium 版本 process.versions.chrome // 返回正在使用的 V8 版本 process.versions.v8 // 返回正在使用的 Node 版本 process.versions.node
支持: Win, macOS, Linux | 進程: Both
Node.js 的 os
模塊提供了有關用戶操做系統的有效信息. 它內置在 Node.js 中, 能夠在主進程和渲染器進程中使用.
在下面的示例中, 咱們經過模塊返回主目錄的位置.
在瀏覽器中查看 完整 os 文檔
渲染器進程
const os = require('os') const homeDir = os.homedir() const sysInfoBtn = document.getElementById('sys-info') sysInfoBtn.addEventListener('click', function () { const message = `當前系統主目錄是: ${homeDir}` document.getElementById('got-sys-info').innerHTML = message })
支持: Win, macOS, Linux | 進程: Both
Electron 的 screen
模塊能夠獲取有關屏幕大小, 顯示, 光標位置等信息. 在下面的示例中, 咱們將獲取所使用的顯示器的尺寸.
在瀏覽器中查看 完整 screen 文檔
渲染器進程
const electronScreen = require('electron').screen const screenInfoBtn = document.getElementById('screen-info') const size = electronScreen.getPrimaryDisplay().size screenInfoBtn.addEventListener('click', function () { const message = `當前屏幕是: ${size.width}px x ${size.height}px` document.getElementById('got-screen-info').innerHTML = message })
尺寸差別.
示例中的 .size
方法返回屏幕的原始尺寸, 但因爲系統菜單欄, 這可能不是您的應用程序的實際可用空間.
要獲取可用屏幕空間的大小, 請使用 .workAreaSize
方法. 而使用 .workArea
方法將返回座標以及可用屏幕空間的尺寸.
若是這邊文章對您有幫助, 感謝 下方點贊 或 Star GitHub: electron-api-demos-Zh_CN 支持, 謝謝.