YouTip LogoYouTip

Electron Network

Electron applications can not only manipulate local resources but also interact with external network services. Whether making HTTP requests, establishing real-time WebSocket connections, or using Node.js's native `net` module, you can perform network communication just like in a browser or on a server. * * * ## HTTP Requests Electron supports both **Browser API (fetch)** and **third-party libraries (axios)**, and can handle cross-origin and authentication issues. * * * ### Using the fetch API `fetch` is a built-in network request interface in modern browsers and Node.js (18+). It supports Promises, has concise syntax, and is suitable for regular data requests. ## Example // GET request example fetch('https://jsonplaceholder.typicode.com/posts/1') .then(response =>{ if(!response.ok)throw new Error('Network response error'); return response.json(); }) .then(data =>{ console.log('Returned data:', data); }) .catch(error =>{ console.error('Request failed:', error); }); **Parameter description:** * `fetch(url, options)`: Initiates a request; * `options.method`: Request method (GET, POST, PUT, DELETE); * `options.headers`: Sets request headers; * `options.body`: Request body, commonly used with POST. POST example: fetch('https://api.example.com/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: 'admin', password: '123456' })}); ### axios Integration `axios` is a powerful HTTP client that supports interceptors, timeouts, concurrency, and other features. It is commonly used in Electron applications to communicate with backend APIs. Installation: npm install axios Usage example: const axios = require('axios');// GET request axios.get('https://jsonplaceholder.typicode.com/users') .then(res => console.log(res.data)) .catch(err => console.error(err));// POST request axios.post('https://api.example.com/data', { name: 'Tom' }) .then(res => console.log('Upload successful', res.data)) .catch(err => console.error('Upload failed', err)); **Parameter description:** * `axios.get(url, config)`: Initiates a GET request; * `axios.post(url, data, config)`: Initiates a POST request; * `config.timeout`: Sets timeout duration; * `config.headers`: Custom request headers. ### Handling Cross-Origin Issues In Electron, because it runs in a desktop environment, there are **no browser CORS restrictions** by default. However, if the frontend page loads web content via `BrowserWindow` and makes requests, cross-origin issues may still be triggered. **Solutions:** **Using `nodeIntegration`:** Make requests in the main process rather than the renderer process. const { ipcMain } = require('electron');const axios = require('axios'); ipcMain.handle('getData', async () => { const res = await axios.get('https://api.example.com/data'); return res.data;}); **Modifying request headers via `session.webRequest`:** const { session } = require('electron'); session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => { details.requestHeaders['Origin'] = '*'; callback({ requestHeaders: details.requestHeaders });}); * * * ## WebSocket Communication WebSocket provides a persistent, full-duplex real-time communication channel, very suitable for applications such as chat, data push, stock quotes, etc. ### WebSocket Client Implementation Electron can directly use the browser's native `WebSocket` API: ## Example const socket =new WebSocket('wss://echo.websocket.org'); socket.onopen=()=>{ console.log('WebSocket connection established'); socket.send('Hello Server!'); }; socket.onmessage=(event)=>{ console.log('Received message:', event.data); }; socket.onclose=()=>{ console.log('Connection closed'); }; **Parameter description:** * `new WebSocket(url)`: Creates a connection; * `socket.send(data)`: Sends a message; * `onmessage`: Listens for server responses; * `onclose`: Listens for connection closure. ### Real-Time Communication Application Example Suppose we build a real-time chat room interface: ## Example const socket =new WebSocket('wss://chat.example.com'); socket.onmessage=(e)=>{ const messageBox = document.getElementById('messages'); messageBox.innerHTML+= `
${e.data}
`; }; function sendMessage(){ const input = document.getElementById('input'); socket.send(input.value); input.value=''; } Renderer process HTML: ## Example
This pattern can easily implement real-time chat, status synchronization, collaborative editing, and other features. * * * ## Native Network Module Electron's main process provides Node.js's `net` module, which allows creating TCP or IPC connections at a lower level, suitable for customized protocols or local service interaction. ### Using the net Module The `net` module allows you to create TCP clients or servers. **Creating a TCP server:** ## Example const net = require('net'); const server = net.createServer(socket =>{ console.log('Client connected'); socket.write('Welcome to the Electron TCP server'); socket.on('data', data =>{ console.log('Received data:', data.toString()); }); }); server.listen(8080,()=>{ console.log('TCP server started, port 8080'); }); **TCP client connection:** ## Example const client = net.createConnection({ port:8080},()=>{ console.log('Connected to server'); client.write('Hello Server!'); }); client.on('data', data =>{ console.log('Server response:', data.toString()); }); **Parameter description:** * `net.createServer(callback)`: Creates a server; * `socket.write(data)`: Sends data; * `socket.on('data')`: Receives data; * `server.listen(port)`: Listens on a port. ### Session Management Electron's `session` module can control network session information such as cache, cookies, and proxy. ## Example const{ session }= require('electron'); const ses = session.defaultSession; // Clear cache ses.clearCache().then(()=> console.log('Cache cleared')); // Set proxy ses.setProxy({ proxyRules:'http=127.0.0.1:8080'}); ### Cookie Handling ## Example const{ session }= require('electron'); const cookies = session.defaultSession.cookies; // Set Cookie cookies.set({ url:'https://example.com', name:'token', value:'abc123', expirationDate:Date.now()/1000+3600 }); // Get Cookie cookies.get({ url:'https://example.com'}) .then(cookies =>{ console.log('Current Cookie:', cookies); }); * * * ## Summary When performing network and external communication in Electron, you can flexibly choose: | Scenario | Recommended Solution | | --- | --- | | Regular HTTP requests | fetch or axios | | Real-time data | WebSocket | | Local or low-level communication | net module | | Managing login status / cache | session + cookies | This multi-level network capability allows Electron applications to access cloud APIs while also coordinating with local services. * * * ## Example The following example is a concise "real-time data dashboard" that can display data fetched from an API in the renderer process, receive WebSocket messages in real-time, and manage login status cookies. ### 1. Project Structure my-electron-network-demo/β”œβ”€β”€ package.json β”œβ”€β”€ main.js # Main process logicβ”œβ”€β”€ preload.js # Preload script└── index.html # Frontend interface ### 2. package.json { "name": "my-electron-network-demo", "version": "1.0.0", "description": "Electron network communication comprehensive example", "main": "main.js", "scripts": { "start": "electron ." }, "devDependencies": { "electron": "latest", "axios": "^1.5.0" }} Install dependencies: npm install ### 3. main.js (Main Process) ## Example const{ app, BrowserWindow, ipcMain, session }= require('electron') const path = require('path') const axios = require('axios') const WebSocket = require('ws') let mainWindow function createWindow(){ mainWindow =new BrowserWindow({ width:900, height:600, webPreferences:{ preload: path.join(__dirname,'preload.js') } }) mainWindow.loadFile('index.html') } // HTTP request example ipcMain.handle('fetch-data', async ()=>{ try{ const res = await axios.get('https://jsonplaceholder.typicode.com/posts/1') return res.data }catch(err){ return{ error: err.message} } }) // WebSocket server example const wss =new WebSocket.Server({ port:8081}) wss.on('connection', ws =>{ console.log('Client connected to WebSocket') ws.send('Welcome to WebSocket real-time data') // Periodic data push const interval = setInterval(()=>{ ws.send(`Real-time message: ${new Date().toLocaleTimeString()}`) },3000) ws.on('close',()=> clearInterval(interval)) }) // Forward WebSocket messages to renderer process ipcMain.handle('connect-ws', async ()=>{ return new Promise(resolve =>{ const ws =new WebSocket('ws://localhost:8081') ws.on('open',()=> console.log('Connected to WebSocket server')) ws.on('message', msg =>{ mainWindow.webContents.send('ws-message', msg.toString()) }) resolve('WebSocket connection established') }) }) // Cookie management example ipcMain.handle('set-cookie', async (event, name, value)=>{ const cookies = session.defaultSession.cookies await cookies.set({ url:'http://localhost', name, value, expirationDate:Date.now()/1000+3600 }) return'Cookie set successfully' }) ipcMain.handle('get-cookie', async (event, name)=>{ const cookies = session.defaultSession.cookies const result = await cookies.get({ url:'http://localhost', name }) return result.length? result.value:null }) app.whenReady().then(()=>{ createWindow() }) ### 4. preload.js (Secure Communication) ## Example const{ contextBridge, ipcRenderer }= require('electron') contextBridge.exposeInMainWorld('electronAPI',{ fetchData:()=> ipcRenderer.invoke('fetch-data'), connectWS:()=> ipcRenderer.invoke('connect-ws'), onWSMessage:(callback)=> ipcRenderer.on('ws-message',(event, msg)=> callback(msg)), setCookie:(name, value)=> ipcRenderer.invoke('set-cookie', name, value), getCookie:(name)=> ipcRenderer.invoke('get-cookie', name) }) ### 5. index.html (Renderer Process Interface) ## Example Electron Network Communication Example

E

← Electron Performance OptimizatElectron Native β†’