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

Electron 1.8.4监听Server Sent Events报错:EventSource未定义,是否支持?

解决Electron 1.8.4中EventSource未定义的问题

嘿,这个问题我之前也踩过坑!其实Electron是支持Server Sent Events(SSE)的,你遇到的EventSource is not defined报错,核心原因是混淆了Electron的主进程和渲染进程环境。

关键知识点:主进程 vs 渲染进程

  • EventSource是浏览器原生API,只存在于Electron的渲染进程(也就是你的HTML页面内嵌的JavaScript代码环境)中。
  • 如果你是在主进程(比如main.js这类启动脚本)里调用new EventSource(),自然会报错——因为主进程基于Node.js环境,默认没有这个浏览器端的API。

两种场景的解决方案

1. 在渲染进程中使用SSE

Electron 1.8.4的渲染进程基于Chromium 59,完全支持标准的EventSource API,直接在HTML页面的<script>标签里写代码即可:

<!-- index.html 中的示例代码 -->
<script>
  const evtSource = new EventSource("https://www.someurl.com/sse");
  
  evtSource.onmessage = function(event) {
    console.log("收到SSE消息:", event.data);
  };
  
  evtSource.onerror = function(error) {
    console.error("SSE连接出错:", error);
    evtSource.close();
  };
</script>

2. 在主进程中使用SSE

如果必须在主进程里处理SSE,可以借助Node.js的第三方包来模拟EventSource功能,比如eventsource:

  • 首先安装依赖:
    npm install eventsource
    
  • 然后在主进程中引入并使用:
    // main.js 中的示例代码
    const EventSource = require('eventsource');
    
    const evtSource = new EventSource("https://www.someurl.com/sse");
    
    evtSource.onmessage = (event) => {
      console.log("主进程收到SSE消息:", event.data);
    };
    
    evtSource.onerror = (error) => {
      console.error("主进程SSE连接出错:", error);
      evtSource.close();
    };
    

最后检查一下

先确认你的代码是运行在主进程还是渲染进程里,调整代码位置或者选择对应的解决方案,就能解决EventSource is not defined的问题啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:39:39