このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docs コミュニティーについてもっと知り、仲間になるにはこちらから。

View in English Always switch to English

EventSource: 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

ブラウザーの互換性

関連情報