Electron Network and External Communication
Electron apps can not only operate on 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 request
Electron supports both browser APIs (fetch) and third-party libraries (axios), and can handle cross-origin and authentication issues.
Using the fetch API
fetch is a network request interface built into modern browsers and Node.js (18+).
It supports Promise, has concise syntax, and suits common 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): initiate a request;options.method: the request method (GET, POST, PUT, DELETE);options.headers: set request headers;options.body: the 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 supporting interceptors, timeouts, concurrency, etc., commonly used for communicating with backend APIs in Electron apps.
Installation:
npm install axios
Usage example:
const axios = require('axios');
// GET 请求
axios.get('https://jsonplaceholder.typicode.com/users')
.then(res => console.log(res.data))
.catch(err => console.error(err));
// POST 请求
axios.post('https://api.example.com/data', { name: 'Tom' })
.then(res => console.log('上传成功', res.data))
.catch(err => console.error('上传失败', err));
Parameter Description:
axios.get(url, config): initiate a GET request;axios.post(url, data, config): initiate a POST request;config.timeout: set the timeout;config.headers: customize request headers.
Handling cross-origin issues
In Electron, because it runs in a desktop environment, by defaultthere is no browser CORS restriction.
but if the front-end page loads web content and makes concurrent requests through BrowserWindow , cross-origin issues may still be triggered.
Solutions:
Use nodeIntegration:
Make requests in the main process instead of 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;
});
Pass session.webRequest Modify request headers:
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, well suited for chat, data push, stock quotes, and similar apps.
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
(
'Message received:'
,
event.
data
)
;
}
;
socket.
onclose
=
(
)
=>
{
console.
log
(
'Connection closed'
)
;
}
;
Parameter Description:
new WebSocket(url): create a connection;socket.send(data): send a message;onmessage: listen for server responses;onclose: listen for connection close.
Real-time communication app example
Suppose we build a real-time chat room UI:
Example
const
socket
=
new
WebSocket
(
'wss://chat.example.com'
)
;
socket.
onmessage
=
(
e
)
=>
{
const
messageBox
=
document.
getElementById
(
'messages'
)
;
messageBox.
innerHTML
+=
`
<
div
$
{e.
data
}
div
`
;
}
;
function
sendMessage
(
)
{
const
input
=
document.
getElementById
(
'input'
)
;
socket.
send
(
input.
value
)
;
input.
value
=
''
;
}
The renderer process HTML:
Example
This pattern easily enables real-time chat, state synchronization, collaborative editing, and more.
Native network modules
Electron's main process provides Node.js's net module, which can directly create TCP or IPC connections at a lower level, suitable for custom protocols or local service interaction.
Using the net module
net The module allows you to create a TCP client or server.
Create 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
(
'Data received:'
,
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): create a server;socket.write(data): send data;socket.on('data'): receive data;server.listen(port): listen on a port.
session management
In Electron, the session module can control network session information such as cache, Cookie, 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 |
|---|---|
| Ordinary HTTP requests | fetch or axios |
| Real-time data | WebSocket |
| Local or low-level communication | net module |
| Manage login state / cache | session + cookies |
This multi-level networking capability allows Electron apps to both access cloud APIs and work together 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-state Cookies.
1. Project structure
my-electron-network-demo/
├── package.json
├── main.js # 主进程逻辑
├── preload.js # 预加载脚本
└── index.html # 前端界面
2. package.json
{
"name": "my-electron-network-demo",
"version": "1.0.0",
"description": "Electron 网络通信综合示例",
"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 connect to WebSocket real-time data'
)
// Push data periodically
const
interval
=
setInterval
(
(
)
=>
{
ws.
send
(
`Real-time message: $
{
new
Date
(
)
.
toLocaleTimeString
(
)
}
`
)
}
,
3000
)
ws.
on
(
'close'
,
(
)
=>
clearInterval
(
interval
)
)
}
)
// Forward WebSocket messages to the 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
[
0
]
.
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 UI)
Example
Electron Network Communication Example
Electron Network Communication Example
6. Run and results
npm start
- Click Get HTTP data: fetch API data via axios and display it on the page.
- Click Connect WebSocket: establish a real-time connection and receive a message every 3 seconds.
- Click Set-Cookie: Creating
tokenCookie. - Click Read Cookie: read and display
tokenvalues.