乐闻世界logo
搜索文章和话题

How to get a unique PC ID via Electron?

1个答案

1

When developing desktop applications with Electron, obtaining a unique machine ID can help with device authentication or security checks. Electron itself does not directly provide an API to obtain the machine ID, but we can leverage Node.js capabilities by using third-party libraries to achieve this.

Method One: Using the node-machine-id Library

The node-machine-id library provides functionality to obtain a machine's unique ID. This ID is generated based on hardware information and remains unchanged even when the operating system is modified. Here is an example of how to use it:

  1. Install node-machine-id

    In your Electron project, install this library using npm or yarn:

    bash
    npm install node-machine-id

    or

    bash
    yarn add node-machine-id
  2. Use it in the Electron Application

    You can use this library in the main process or renderer process. Here is an example of obtaining the machine ID in the Electron main process:

    javascript
    const { app } = require('electron'); const { machineIdSync } = require('node-machine-id'); app.on('ready', () => { let machineId = machineIdSync(); console.log(`Machine ID: ${machineId}`); });

    This code prints the machine's unique ID when the application is ready.

Method Two: Using System Commands

For more advanced users, you can directly execute system commands in Node.js to obtain hardware information and generate a unique ID from it. However, this method typically relies on specific operating system commands, so you may need to write different code for different systems.

For example, on Windows systems, you can use the wmic command to obtain hardware information:

javascript
const { exec } = require('child_process'); const { app } = require('electron'); app.on('ready', () => { exec('wmic csproduct get UUID', (error, stdout) => { if (error) { console.error(`Command execution failed: ${error}`); return; } console.log(`Computer UUID: ${stdout.trim()}`); }); });

When using this method, ensure your application has permission to execute system commands and consider cross-platform compatibility issues.

Summary

By using either of the above methods, you can obtain the machine's unique ID in an Electron application. The node-machine-id library provides a simple and universal approach, while directly using system commands requires more customization but may be more flexible. Choose the appropriate method based on your specific requirements.

2024年6月29日 12:07 回复

你的答案