WebSocket: binaryType プロパティ

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

メモ: この機能はウェブワーカー内で利用可能です。

WebSocket.binaryType プロパティは、この WebSocke 接続によって受信されているバイナリーデータの型を制御します。

文字列です。

"blob"

バイナリーデータに Blob オブジェクトを使用します。これが既定値です。

"arraybuffer"

バイナリーデータに ArrayBuffer オブジェクトを使用します。

js
// WebSocket 接続を作成
const socket = new WebSocket("ws://localhost:8080");

// バイナリーの型を "blob" から "arraybuffer" に変更
socket.binaryType = "arraybuffer";

// メッセージを待ち受け
socket.addEventListener("message", (event) => {
  if (event.data instanceof ArrayBuffer) {
    // バイナリーフレーム
    const view = new DataView(event.data);
    console.log(view.getInt32(0));
  } else {
    // テキストフレーム
    console.log(event.data);
  }
});

仕様書

Specification
WebSockets
# ref-for-dom-websocket-binarytype①

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
binaryType

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support