Skip to content

Electron Skill

🤖 AI Integration Guide: Send this page link to AI for automatic integration guidance

Quick Information

  • Application Type: Electron
  • Skill Version: 2.0.0
  • Integration Difficulty: ⭐⭐ (Easy)
  • Estimated Time: 15-30 minutes

📖 Integration Scenarios

Choose the appropriate integration method based on your project type:

ScenarioSuitable ForFeaturesEstimated Time
Scenario 1Non-open source, Private projectsManual build & upload, Data reporting15 minutes
Scenario 2Open source projectsGitHub Actions automated build & release30 minutes

Scenario 1: Non-Open Source Project Integration

Suitable for private projects or projects that don't require GitHub Actions automated deployment.

1. Install Dependencies

bash
npm install electron-updater

2. Create dev-update.yml

Create dev-update.yml in your project root:

yaml
provider: generic
updaterCacheDirName: your-app-updater

3. Add Main Process Code

typescript
import { autoUpdater } from 'electron-updater';
import { app } from 'electron';

async function checkForUpdates() {
  const FeedURL = `https://api.upgrade.toolsetlink.com/v1/electron/upgrade?electronKey=YOUR_ELECTRON_KEY&versionName=${app.getVersion()}&appointVersionName=&devModelKey=&devKey=&platform=${process.platform}&arch=${process.arch}`;
  
  autoUpdater.setFeedURL({
    url: FeedURL,
    provider: 'generic',
  });
  
  autoUpdater.requestHeaders = {
    'X-AccessKey': 'YOUR_ACCESS_KEY',
  };
  
  const result = await autoUpdater.checkForUpdates();
  return result;
}

async function downloadUpdate() {
  const result = await checkForUpdates();
  if (result?.updateInfo) {
    autoUpdater.setFeedURL({
      url: result.updateInfo.path,
      provider: 'generic',
    });
    await autoUpdater.downloadUpdate();
  }
}

⚠️ Note: Replace YOUR_ELECTRON_KEY and YOUR_ACCESS_KEY with your actual keys

4. Data Reporting Integration

During the upgrade process, call the data reporting API to record upgrade status for data statistics and analysis.

Reporting Utility Function

typescript
import crypto from 'crypto';

function generateSignature(timestamp: string, nonce: string, body: string, accessSecret: string): string {
  const signStr = `timestamp=${timestamp}&nonce=${nonce}&body=${body}&accessSecret=${accessSecret}`;
  return crypto.createHash('md5').update(signStr).digest('hex');
}

function generateNonce(length: number = 16): string {
  return crypto.randomBytes(Math.ceil(length / 2)).toString('hex').slice(0, length);
}

async function reportEvent(
  eventType: string,
  appKey: string,
  eventData: Record<string, any>,
  accessKey: string,
  accessSecret: string
): Promise<void> {
  const timestamp = new Date().toISOString();
  const nonce = generateNonce();
  const body = JSON.stringify({
    eventType,
    timestamp,
    appKey,
    eventData,
  });
  
  const signature = generateSignature(timestamp, nonce, body, accessSecret);
  
  try {
    const response = await fetch('https://api.upgrade.toolsetlink.com/v1/app/report', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Timestamp': timestamp,
        'X-Nonce': nonce,
        'X-AccessKey': accessKey,
        'X-Signature': signature,
      },
      body,
    });
    
    const result = await response.json();
    console.log('Report result:', result);
  } catch (error) {
    console.error('Report failed:', error);
  }
}

Download Event Reporting

typescript
function reportDownload(downloadVersionCode: number, code: number) {
  reportEvent(
    'app_upgrade_download',
    'YOUR_ELECTRON_KEY',
    {
      versionCode: parseInt(app.getVersion().split('.').join('')),
      downloadVersionCode,
      code,
      target: process.platform,
      arch: process.arch,
    },
    'YOUR_ACCESS_KEY',
    'YOUR_ACCESS_SECRET'
  );
}

Upgrade Complete Event Reporting

typescript
function reportUpgrade(upgradeVersionCode: number, code: number) {
  reportEvent(
    'app_upgrade_upgrade',
    'YOUR_ELECTRON_KEY',
    {
      versionCode: parseInt(app.getVersion().split('.').join('')),
      upgradeVersionCode,
      code,
      target: process.platform,
      arch: process.arch,
    },
    'YOUR_ACCESS_KEY',
    'YOUR_ACCESS_SECRET'
  );
}

Complete Upgrade Flow Example

typescript
import { autoUpdater } from 'electron-updater';
import { app, BrowserWindow } from 'electron';

let upgradeVersionCode = 0;

autoUpdater.on('download-progress', (progressObj) => {
  console.log(`Download progress: ${progressObj.percent}%`);
});

autoUpdater.on('update-downloaded', (info) => {
  console.log('Download complete:', info.version);
  upgradeVersionCode = parseInt(info.version.split('.').join(''));
  
  reportDownload(upgradeVersionCode, 0);
  
  const win = BrowserWindow.getFocusedWindow();
  if (win) {
    win.webContents.send('update-downloaded', info);
  }
});

autoUpdater.on('error', (error) => {
  console.error('Update error:', error);
  
  if (upgradeVersionCode > 0) {
    reportDownload(upgradeVersionCode, 1);
  }
});

function reportAppStart() {
  reportEvent(
    'app_start',
    'YOUR_ELECTRON_KEY',
    {
      versionCode: parseInt(app.getVersion().split('.').join('')),
      launchTime: new Date().toISOString(),
      target: process.platform,
      arch: process.arch,
    },
    'YOUR_ACCESS_KEY',
    'YOUR_ACCESS_SECRET'
  );
}

app.whenReady().then(() => {
  reportAppStart();
});

Status Code Reference

Download event code:

Status CodeDescription
0Download successful
1Download failed (general)
1001HTTP error
1002Insufficient space
1003File operation error
1004MD5 verification failed

Upgrade event code:

Status CodeDescription
0Upgrade successful
1Upgrade failed

📖 Detailed API Documentation: Event Reporting API

5. Manual Build and Upload

Build Application

bash
npm run build

Generated Files

PlatformFiles
macOS.dmg, .zip, latest-mac.yml
Windows.exe, .msi, latest.yml
Linux.AppImage, .deb, latest-linux.yml
  1. Log in to UpgradeLink dashboard
  2. Go to Application Management page
  3. Create a new version, upload the corresponding installation package and yml files
  4. Configure upgrade strategy

Scenario 2: Open Source Project Integration

Suitable for open source projects that require GitHub Actions automated build, release, and update.

1. Complete Basic Integration

First complete all steps (1-4) in Scenario 1.

2. Configure GitHub Secrets

Add the following encrypted environment variables in your GitHub repository's Settings > Security > Secrets and variables > Actions:

Secret NameDescriptionHow to Get
UPGRADE_LINK_ACCESS_KEYUpgradeLink access keyUpgradeLink dashboard > Key Management
UPGRADE_LINK_ELECTRON_KEYElectron application unique identifierUpgradeLink dashboard > Application Info

3. Configure GitHub Actions Workflow

Create .github/workflows/publish.yml in your project root:

yaml
name: 'publish'

on:
  push:
    branches:
      - main
    tags:
      - '*.*.*'

jobs:
  electron-build:
    outputs:
      appVersion: ${{ steps.extract-version.outputs.appVersion }}
    permissions:
      contents: write
    strategy:
      fail-fast: false
      matrix:
        include:
          - platform: ubuntu-22.04
            target: x86_64-unknown-linux-gnu
            artifact-name: ubuntu-x86_64
            arch-suffix: x64
            build-command: "yarn electron-builder --linux --x64 --publish always --config.publish.channel=latest-linux"

          - platform: ubuntu-22.04
            target: aarch64-unknown-linux-gnu
            artifact-name: ubuntu-aarch64
            arch-suffix: arm64
            build-command: "yarn electron-builder --linux --arm64 --publish always --config.publish.channel=latest-linux"

          - platform: macos-latest
            target: aarch64-apple-darwin
            artifact-name: macos-arm64
            arch-suffix: arm64
            build-command: "yarn electron-builder --mac --arm64 --publish always --config.publish.channel=latest-mac"

          - platform: macos-latest
            target: x86_64-apple-darwin
            artifact-name: macos-x64
            arch-suffix: x64
            build-command: "yarn electron-builder --mac --x64 --publish always --config.publish.channel=latest-mac"

          - platform: windows-latest
            target: x86_64-pc-windows-msvc
            artifact-name: windows-x64
            arch-suffix: x64
            build-command: "yarn electron-builder --win --x64 --publish always --config.publish.channel=latest-win"

    runs-on: ${{ matrix.platform }}
    steps:
      - uses: actions/checkout@v4

      - name: setup node
        uses: actions/setup-node@v4
        with:
          node-version: lts/*
          cache: 'yarn'

      - name: Install dependencies
        run: yarn install

      - name: Build Electron App
        run: ${{ matrix.build-command }}
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Extract version
        id: extract-version
        run: |
          if [[ "${{ github.ref }}" == refs/tags/* ]]; then
            VERSION=${{ github.ref_name }}
          else
            VERSION=$(node -p "require('./package.json').version")
          fi
          echo "appVersion=$VERSION" >> $GITHUB_OUTPUT
          echo "Extracted version: $VERSION"
        shell: bash

      - name: Upload artifacts
        uses: actions/upload-artifact@v4.0.0
        with:
          name: ${{ matrix.artifact-name }}
          path: dist/*
          if-no-files-found: error

  electron-release:
    needs: electron-build
    runs-on: ubuntu-22.04
    permissions:
      contents: write
    steps:
      - name: Download all artifacts
        uses: actions/download-artifact@v4
        with:
          path: artifacts
          merge-multiple: false

      - name: Prepare release files
        run: |
          mkdir -p release-files
          find artifacts -type f -exec cp {} release-files/ \;
          echo "Files to release:"
          ls -l release-files

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v1
        with:
          tag_name: ${{ needs.electron-build.outputs.appVersion }}
          name: Release ${{ needs.electron-build.outputs.appVersion }}
          files: release-files/*
          draft: false
          prerelease: false
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

  upgradeLink-upload:
    needs: [electron-build, electron-release]
    permissions:
      contents: write
    runs-on: ubuntu-latest
    steps:
      - name: Send a request to UpgradeLink
        uses: toolsetlink/upgradelink-action-electron@v1.0.1
        with:
          source-url: 'https://github.com/${{ github.repository }}/releases/download/${{ needs.electron-build.outputs.appVersion }}'
          access-key: ${{ secrets.UPGRADE_LINK_ACCESS_KEY }}
          electron-key: ${{ secrets.UPGRADE_LINK_ELECTRON_KEY }}
          github-token: ${{ secrets.GITHUB_TOKEN }}
          version: ${{ needs.electron-build.outputs.appVersion }}
          prompt-upgrade-content: 'New version available, please upgrade'

4. Workflow Details

electron-build Job

Function: Cross-platform build of Electron application

StepDescription
Checkout codeactions/checkout@v4
Setup Node.jsSet Node.js LTS version
Install dependenciesyarn install
Build applicationBuild using electron-builder
Extract versionExtract from tag or package.json
Upload artifactsUpload build artifacts for later use

Multi-platform Build Strategy:

PlatformRunnerArchitecture
Linux (x64)ubuntu-22.04x64
Linux (ARM)ubuntu-22.04arm64
macOS (M1+)macos-latestarm64
macOS (Intel)macos-latestx64
Windowswindows-latestx64

electron-release Job

Function: Create GitHub Release and upload installation packages

StepDescription
Download artifactsDownload all build artifacts from electron-build
Prepare filesOrganize release files
Create ReleaseCreate release using softprops/action-gh-release

Function: Sync update information to UpgradeLink platform

StepDescription
Wait for buildDepends on electron-build and electron-release completion
Get versionRetrieve from electron-build output
Upload infoSync using upgradelink-action-electron

UpgradeLink Action Parameters:

ParameterDescription
source-urlGitHub Releases address
access-keyUpgradeLink access key
electron-keyElectron application unique identifier
github-tokenGitHub Token
versionApplication version number
prompt-upgrade-contentUpgrade prompt content

Configure the GitHub repository address in UpgradeLink dashboard:

  1. Log in to UpgradeLink dashboard
  2. Go to Application Management > Electron Application Details
  3. Fill in the repository address in the "GitHub Repository Address" field, e.g.: https://github.com/username/repo-name
  4. Save configuration

6. Automated Process Description

When code is pushed to the main branch, the automated process is as follows:

Code Push


┌─────────────────────────────────────────┐
│         electron-build Job               │
│  ┌─────────────────────────────────┐    │
│  │ Parallel build for 5 platforms   │    │
│  │ - Linux (x64)                   │    │
│  │ - Linux (ARM)                   │    │
│  │ - macOS (M1)                    │    │
│  │ - macOS (Intel)                 │    │
│  │ - Windows                       │    │
│  └─────────────────────────────────┘    │
└─────────────────────────────────────────┘


┌─────────────────────────────────────────┐
│        electron-release Job              │
│  ┌─────────────────────────────────┐    │
│  │ Create GitHub Release            │    │
│  │ Upload packages & yml files      │    │
│  └─────────────────────────────────┘    │
└─────────────────────────────────────────┘


┌─────────────────────────────────────────┐
│       upgradeLink-upload Job             │
│  ┌─────────────────────────────────┐    │
│  │ Read GitHub Releases             │    │
│  │ Call UpgradeLink API             │    │
│  │ Auto-create version & strategy   │    │
│  └─────────────────────────────────┘    │
└─────────────────────────────────────────┘


Users receive update notification

🤖 AI Integration

Send this page link to AI:

Please help me integrate Electron application upgrade, here's the Skill link:
https://www.toolsetlink.com/en/upgrade/skill/electron

AI will automatically:

  1. Identify the application type as Electron
  2. Determine project type (open source/non-open source)
  3. Retrieve configuration information and code examples
  4. Guide you to replace placeholders
  5. Verify configuration correctness
  6. Complete integration testing

📋 Complete Example

View complete example project: electron-demo


❓ FAQ

Q: How to get Electron Key?

A: Log in to UpgradeLink dashboard, create an Electron application to obtain it.

Q: How to get Access Key and Access Secret?

A: Log in to UpgradeLink dashboard, obtain them from the key management page.

Q: What if update fails?

A: Check network connection and configuration, or contact AI for help.

Q: Will data reporting failure affect the upgrade process?

A: No. Data reporting is an asynchronous operation, failure will not affect the normal upgrade process. It is recommended to retry during off-peak hours.

Q: macOS application signing issues?

A: macOS applications must be signed for auto-update to work. Please refer to Electron Builder Documentation.

Q: What if GitHub Actions build fails?

A:

  1. Check GitHub Actions logs for specific error information
  2. Confirm all dependencies are correctly installed
  3. Ensure Node.js version is compatible
  4. Check if GitHub Secrets are configured correctly

📚 Reference Resources

toolsetlink@163.com