Electron Network and External Communication

Electron applications can not only operate on local resources, but also interact with external network services.
Whether initiating HTTP requests, establishing real-time WebSocket connections, or using Node.js nativenetmodules, you can perform network communication just like in a browser or on a server.


HTTP request

Electron also supportsBrowser API (fetch)andThird-party library (axios)and can handle cross-origin and authentication issues.


Using fetch API

fetchis the network request interface built into modern browsers and Node.js (18+).
It supports Promise, has a clean syntax, and is suitable for routine 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('Return data:', data);
  })
  .catch(error => {
    console.error('Request failed:', error);
  });

Parameter description:

  • fetch(url, options): Initiate request;
  • options.method: Request method (GET, POST, PUT, DELETE);
  • options.headers: Set request headers;
  • options.bodyRequest body, often used in POST requests.

POST example:

fetch('https://api.example.com/login', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ username: 'admin', password: '123456' })
});

axios integration

axiosis a powerful HTTP client that supports interceptors, timeouts, concurrency, and other features, commonly used in Electron applications to communicate with backend APIs.

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)Make a GET request;
  • axios.post(url, data, config)Make a POST request;
  • config.timeoutSet the timeout;
  • config.headersCustom request headers.

Handle cross-origin issues

In Electron, because it runs in a desktop environment, by defaultThere are no browser CORS restrictions.。
But if the frontend page passes throughBrowserWindowLoading web content and making requests may still trigger cross-origin issues.

Solution:

UsagenodeIntegration:
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;
});

Throughsession.webRequestModify 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, ideal for applications such as chat, data push, and stock quotes.

WebSocket Client Implementation

Electron can directly use the browser's nativeWebSocket 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): Create connection;
  • socket.send(data): Send message;
  • onmessageListen for server response;
  • oncloseListen for connection close.

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 += `<div>${e.data}</div>`;
};

function sendMessage() {
  const input = document.getElementById('input');
  socket.send(input.value);
  input.value = '';
}

Renderer process HTML:

Example

<input id="input" placeholder="Input Message">
<button onclick="sendMessage()">send</button>
<div id="messages"></div>

This pattern can easily implement real-time chat, state synchronization, collaborative editing, and other features.


Native network module

Electron's main process provides Node.jsnetmodules can directly create TCP or IPC connections at a lower level, suitable for custom protocols or local service interaction.

net module usage

netThe module allows you to create TCP clients or servers.

Create a TCP server:

Example

const net = require('net');

const server = net.createServer(socket => {
  console.log('Client connected');
  socket.write(Welcome to 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): Create server;
  • socket.write(data): Send data;
  • socket.on('data'): Receive data;
  • server.listen(port): Listen on port.

session management

In ElectronsessionThe module can control network session information such as cache, cookies, proxy, and more.

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:

Scenarios 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-layered network capability allows Electron applications to both access cloud APIs and work in coordination with local services.


Example

The following example is a concise "real-time data dashboard" that can display data fetched from the API in the renderer process, receive WebSocket messages in real time, and manage login-state cookies.

I. 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')
  // Scheduled data push
  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 Interface)

Example

<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>Electron network communication example</title>
  <style>
    body { font-family: sans-serif; padding: 20px; }
    button { margin: 5px; padding: 10px 20px; cursor: pointer; }
    #output { margin-top: 20px; }
  </style>
</head>
<body>
  <h1>Electron network communication example</h1>

  <button id="fetchBtn">Fetch HTTP data</button>
  <button id="wsBtn">Connect WebSocket</button>
  <button id="setCookieBtn">Set Cookie</button>
  <button id="getCookieBtn">Read Cookie</button>

  <div id="output"></div>

  <script>
    const output = document.getElementById('output')

    document.getElementById('fetchBtn').addEventListener('click', async () => {
      const data = await window.electronAPI.fetchData()
      output.innerHTML += `<p>HTTP returned data: ${JSON.stringify(data)}</p>`
    })

    document.getElementById('wsBtn').addEventListener('click', async () => {
      await window.electronAPI.connectWS()
      output.innerHTML += `<p>WebSocket connection established</p>`
    })

    window.electronAPI.onWSMessage(msg => {
      output.innerHTML += `<p>WebSocket message: ${msg}</p>`
    })

    document.getElementById('setCookieBtn').addEventListener('click', async () => {
      const res = await window.electronAPI.setCookie('token', 'abc123')
      output.innerHTML += `<p>${res}</p>`
    })

    document.getElementById('getCookieBtn').addEventListener('click', async () => {
      const value = await window.electronAPI.getCookie('token')
      output.innerHTML += `<p>Cookie token value: ${value}</p>`
    })
  </script>
</body>
</html>

VI. Running and Effects

npm start
  • ClickFetch HTTP data: Fetch API data via axios and display it on the page.
  • ClickConnect WebSocket: Establish a real-time connection and receive a message every 3 seconds.
  • ClickSet Cookie: createtoken Cookie。
  • ClickRead Cookie: Read and displaytokenvalue.
other extensions