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 を返します。
構文
js
new EventSource(url)
new EventSource(url, options)
引数
url-
文字列で、イベント/メッセージを処理するリモートリソースの場所を表します。
options省略可-
新しいコネクションを構成するオプションを提供します。可能な項目は次のとおりです。
withCredentials省略可-
論理値で、既定値は
falseであり、 CORS の資格情報をincludeに設定すべきかどうかを示します。
例
js
const evtSource = new EventSource("sse.php");
const eventList = document.querySelector("ul");
evtSource.onmessage = (e) => {
const newElement = document.createElement("li");
newElement.textContent = `message: ${e.data}`;
eventList.appendChild(newElement);
};
メモ: 完全な例は GitHub で見られます。 PHP を用いた簡単な SSE のデモ を参照してください。
仕様書
| Specification |
|---|
| HTML> # dom-eventsource-dev> |
ブラウザーの互換性
Loading…