EventSource()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2020年1月.
EventSource() 构造函数返回一个新建的EventSource,它代表了一个远程资源。
语法
pc = new EventSource(url, configuration);
参数
url-
一个
USVString,它代表远程资源的位置 configuration可选-
为配置新连接提供选项。可选项是:
withCredentials,默认为false,指示 CORS 是否应包含凭据 ( credentials )。
返回值
一个新建的 EventSource 对象,如果指定了configuration,则按其配置;否则,配置为合适的基本默认值。
示例
js
var evtSource = new EventSource("sse.php");
var eventList = document.querySelector("ul");
evtSource.onmessage = function (e) {
var newElement = document.createElement("li");
newElement.textContent = "message: " + e.data;
eventList.appendChild(newElement);
};
备注:你可以在 GitHub 查看完整示例 — 请查看 Simple SSE demo using PHP.
规范
| Specification |
|---|
| HTML> # dom-eventsource-dev> |