You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Electron应用中处理tel:协议?

解决Windows下Electron 28.2.1处理tel://链接的问题

核心问题说明

protocol.handle仅支持自定义协议,而tel是Windows系统预注册的协议,直接调用该API无法让你的应用出现在打开列表中。必须通过注册表注册应用为tel协议的可选处理程序,同时在Electron中监听协议激活事件。

分步解决方案

1. 开发环境临时注册注册表

Windows需要将你的Electron开发包路径写入注册表,以管理员身份打开CMD,执行以下命令(替换YOUR_ELECTRON_EXE_PATH为本地Electron的exe路径,例:.\node_modules\electron\dist\electron.exe):

reg add HKEY_CLASSES_ROOT\tel\shell\open\command /ve /d "\"YOUR_ELECTRON_EXE_PATH\" \"%1\"" /f
reg add HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\tel\UserChoice /v Progid /d tel /f

注:开发环境下重启电脑后可能需要重新执行,也可以写个bat脚本自动完成。

2. Electron主进程监听激活事件

注册表注册后,需要监听应用的启动/激活事件来捕获tel链接,主进程代码示例:

const { app, BrowserWindow, ipcMain } = require('electron');
let mainWindow;

function createMainWindow() {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  });
  mainWindow.loadFile('index.html');
}

// 应用已打开时,处理外部tel链接激活
app.on('second-instance', (event, commandLine) => {
  const telUrl = commandLine.at(-1);
  if (telUrl.startsWith('tel:')) {
    console.log('收到tel链接:', telUrl);
    // 业务逻辑:恢复窗口、传递链接到渲染进程
    if (mainWindow) {
      mainWindow.isMinimized() && mainWindow.restore();
      mainWindow.focus();
      mainWindow.webContents.send('tel-link-received', telUrl);
    }
  }
});

// 应用未打开时,通过tel链接启动应用
app.on('open-url', (event, url) => {
  event.preventDefault();
  if (url.startsWith('tel:')) {
    console.log('启动时处理tel链接:', url);
    if (!mainWindow) {
      createMainWindow();
      mainWindow.webContents.on('did-finish-load', () => {
        mainWindow.webContents.send('tel-link-received', url);
      });
    } else {
      mainWindow.webContents.send('tel-link-received', url);
    }
  }
});

app.whenReady().then(() => {
  createMainWindow();
  app.on('activate', () => {
    BrowserWindow.getAllWindows().length === 0 && createMainWindow();
  });
});

app.on('window-all-closed', () => {
  process.platform !== 'darwin' && app.quit();
});

渲染进程(index.html)接收链接示例:

<script>
const { ipcRenderer } = require('electron');
ipcRenderer.on('tel-link-received', (event, url) => {
  const phoneNumber = url.replace('tel:', '');
  alert(`处理电话号码:${phoneNumber}`);
  // 这里添加你的业务逻辑
});
</script>

3. 打包时自动注册协议(electron-builder)

如果使用electron-builder打包,在package.json中配置协议,打包后会自动写入Windows注册表:

{
  "build": {
    "win": {
      "fileAssociations": [
        {
          "protocol": "tel",
          "name": "Tel链接处理工具",
          "role": "Viewer"
        }
      ]
    }
  }
}

排查要点

  • 必须以管理员权限执行注册表命令,否则无法写入系统注册表项
  • 测试前重启浏览器/资源管理器,确保注册表变更生效
  • 若系统默认tel处理程序为其他应用,可在「Windows设置-应用-默认应用-按协议选择应用」中手动切换到你的应用

内容的提问来源于stack exchange,提问作者Ali Sherafat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 16:12:17