Level up your Twilio API skills in TwilioQuest, an educational game for Mac, Windows, and Linux. Download Now


Rate this page:

Thanks for rating this page!

We are always striving to improve our documentation quality, and your feedback is valuable to us. How could this documentation serve you better?

Twilio Client JS SDK: Twilio.Connection


// Explicitly create a new outgoing connection
var connection = Twilio.Device.connect();

// or handle an incoming connection event
Twilio.Device.on('incoming', function(conn) {
  // conn is a Twilio.Connection object


.accept( [audioConstraints] )



Twilio.Device.on('incoming', function(conn) {


var audioConstraints = {
  optional: [{ sourceId: 'XXX' }]

Twilio.Device.on('incoming', function(conn) {


pending の接続を拒否します。 クライアント セッションから発信者へ、通話終了が発行されます。 複数のクライアント セッションがアクティブな場合、pending の接続はすべてについて拒否されます。






boolean パラメーターを元にした現在の接続を Mute / Unmute します。


接続がMuteかどうかを示すboolean を返します。


Get the local MediaStream being used by the Connection. This contains the local Client's audio input.


Get the remote MediaStream. This contains the remote Client's audio, which is being received locally and output through the local Client's speakers.

.sendDigits( digits )

DTMFトーンを再生します。digitsパラメーターは文字列であり、0-9*#、およびwを含むことができます。 各wは番号との間に500ミリ秒の一時停止を発生させます。 もしTwiMLに馴染みがある場合、sendDigitsメソッドを<code>&lt;Number&gt;</code>名詞のsendDigits属性と考えることができます。 SDKはDTMF番号の送信のみをサポートします。 入力オーディオストリームにDTMF信号が存在する場合、イベントは発生しません。



"pending" 接続は着信中で、まだ確立されていません。
"connecting" The connection has been accepted by or initiated by the local client.
"ringing" The callee has been notified of the call but has not yet responded.

Note: Until 2.0, this state is only surfaced when the enableRingingState flag is set to true in Device.setup options and the TwiML app is dialing out with the answerOnBridge property, eg: <Dial answerOnBridge=true></Dial>.
"open" 接続は確立されています。
"closed" 接続は終了されました。

.postFeedback(score, issue)

Posts the feedback collected for this call to Twilio. If no parameters are passed, Twilio will report feedback was not available for this call. Posting the feedback using this API will enable you to understand exactly which factors contribute to audio quality problems. Twilio will be able to correlate the metrics with perceived call quality and provide an accurate picture of the factors affecting your users’ call experience.

Score Suggested Interpretation
1 Terrible call quality, call dropped, or caused great difficulty in communicating.
2 Bad call quality, like choppy audio, periodic one-way-audio.
3 Average call quality, manageable with some noise/minor packet loss.
4 Good call quality, minor issues.
5 Great call quality. No issues.
Issue Name 概要
dropped-call 通話は最初は繋がったが、やがて終了した
audio-latency Participants can hear each other but with significant delay
one-way-audio One participant couldn’t hear the other
choppy-audio Periodically, participants couldn’t hear each other. Some words were lost.
noisy-call There was disturbance, background noise, low clarity.
echo There was echo during call.
.postFeedback(5); // Perfect call!
.postFeedback(2, 'dropped-call'); // Not so perfect... We'll do better next time!
.postFeedback(); // We asked the customer for feedback but they declined to provide feedback.

Event Reference

.on('accept', handler(connection))


ハンドラー関数は、Twilio.Connection オブジェクト 1 つだけを引数に取ります。

.on('disconnect', handler(connection))


ハンドラー関数は、Twilio.Connection オブジェクト 1 つだけを引数に取ります。

var connection = Twilio.Device.connect();

connection.on('disconnect', function(conn) {
  console.log("the call has ended");

.on('error, handler(error))

デバイスエラーがこの接続の継続期間中に起きた場合、ハンドラーファンクションを登録します。これらは、リクエスト中、ケイパビリティトークン、接続エラー、その他アプリケーションエラー のエラーとなります。詳しい情報はTwilo Clientエラーコードリファレンスをご覧ください。エラーハンドラーを確認することにより、アプリケーションのデバック、コード中のミスを発見する手助けになります。

ハンドラー関数は error オブジェクトを引数に取ります。 error オブジェクトには、次のプロパティがあります。

プロパティ 概要
message エラーを説明する文字列です。
code Twilio クライアント エラー コード リファレンスに記載されているエラー コード番号です。
connection エラーが起きた際、Twilio.Connectionオブジェクトはアクティブであることを参考にして下さい。
twilioError When applicable, errors emitted now contain this twilioError field, providing more information about the error. This twilioError represents the new TwilioError format that will become the default Error format in the next major release. To get a list of possible twilioErrors, please visit this page.

.on('mute', handler(boolean, connection))

Mute / Unmute時に随時呼び出されるハンドラー関数を登録します。


.on('reconnecting', handler(error))

Note: This feature is behind a flag on Device.setup: enableIceRestart. By default, this event will not fire.

Raised when media connection fails and automatic reconnection has been started by issuing ICE Restarts. During this period, Connection.status() will be set to reconnecting.

  • error - Error object { code: 53405, message: 'Media connection failed.' }
  • Media reconnection triggers
    • ICE Connection state transitions to disconnect and bytes sent and received in the last 3 seconds is zero.
    • ICE Connection state or PeerConnection state transitions to failed. Only Chrome browser will attempt an ICE restart with this trigger. Other browsers will immediately disconnect the call and raise an error 31003. This is due to browsers not fully supporting connection states during an ICE restart.
  • Retries - ICE restarts will be retried in the event that previous ICE restarts are unsuccessful. Retry attemps will happen when ICE Connection state or PeerConnection state transitions to failed. If more than 30 seconds has elapsed during this transition, the call will disconnect and raise an error 31003.

.on('reconnected', handler())

Note: This feature is behind a flag on Device.setup: enableIceRestart. By default, this event will not fire.

Raised when media connection has been restored which is detected when media starts flowing. Once reconnected, Connection.status() will be set to open.

.on('ringing', handler(hasEarlyMedia))

Note: This feature is behind a flag on Device.setup: enableRingingState. By default, this event will not fire.

Raised when the Connection has entered the ringing state. By default, TwiML's Dial verb will connect immediately and this state will be brief or skipped entirely. When using the Dial verb with answerOnBridge=true, the ringing state will begin when the callee has been notified of the call and will transition into open after the callee accepts the call, or closed if the call is rejected or cancelled.

The hasEarlyMedia argument is a boolean denoting whether there is early media available from the callee. If true, the Client SDK will automatically play the early media -- Sometimes this is ringing, other times it may be an important message about the call. If false, there is no remote media to play, so the application may want to play its own outgoing ringtone sound.

connection.on('ringing', function(hasEarlyMedia) {
  if (hasEarlyMedia) { playOutgoingRinging(); }

.on('sample', handler(rtcSample)

Register a handler function to be called when the Connection gets a WebRTC sample object. This event is published every second.

Example Data
  "timestamp": 1558028696403.511,
  "totals": {
    "packetsReceived": 41,
    "packetsLost": 0,
    "packetsSent": 137,
    "packetsLostFraction": 0,
    "bytesReceived": 6046,
    "bytesSent": 10967
  "bytesReceived": 453,
  "bytesSent": 385,
  "packetsSent": 50,
  "packetsReceived": 32,
  "packetsLost": 0,
  "packetsLostFraction": 0,
  "jitter": 48,
  "rtt": 80,
  "mos": 4.291574747736576,
  "codecName": "opus"

.on('volume', handler(inputVolume, outputVolume))

Register a handler function to be called with the Connection’s current input volume and output volume on every animation frame. The handler will be invoked up to 60 times per second, and will scale down dynamically on slower devices to preserve performance. The handler receives inputVolume and outputVolume as percentages of maximum volume represented by a floating point number between 0.0 and 1.0, inclusive. This value represents a range of relative decibel values between -100dB and -30dB.

.on('warning', handler(warningName))

Raised when a call-quality-metric has crossed a threshold.

Twilio.js raises warning events when it detects a drop in call quality or other conditions that may indicate the user is having trouble with the call. You can implement callbacks on these events to alert the user of an issue.

For a full list of warning events, check the Voice Insights events reference. Check the examples below to see how to listen to warning and warning-cleared events.

connection.on('warning', function(warningName) {
  if (warningName === 'low-mos') {
    showQualityWarningModal('We have detected poor call quality conditions. You may experience degraded call quality.');

.on('warning-cleared', handler(warningName))

Raised when a call-quality-metric has returned to normal.

connection.on('warning-cleared', function(warningName) {
  if (warningName === 'low-mos') {



.customParameters is a Map<string, string> that includes all TwiML parameters sent to or received from the TwiML app this Connection is connecting to. This feature is a great way to pass context data between your TwiML app and the JS Client SDK.

On incoming Connections

An incoming Connection's .customParameters contains all of the data sent using <Parameter> nouns in the TwiML app.

On outgoing Connections

An outgoing Connection's .customParameters contains all of the TwiML params data passed in to Device.connect(twimlParams). It's important to note that a caller's .customParameters Map and a callee's .customParameters Map may not contain the same data, because it's up to your TwiML app to choose which, if any, of the data it receives from the caller to pass to the callee.


.parameters 誰が発信して、何をダイヤルしたかのような通話の情報の詳細を含みます。これらのパラメーターの意味はTwilio Voice リクエストのパラメータと一致します。

incoming .parameters


パラメーター 概要
CallSid Twilio が生成したこの通話のユニークな識別子です。
AccountSid あなたのTwilio Account ID。ACから始まる34文字の文字列です。
From 発信者(相手側)の電話番号、または クライアント識別子 です。書式は E.164形式 (+で始まり国番号が続く形式) です。


クライアント識別子は、 client: で始まるURLスキームで、例えば、'tommy' という名前のクライアントからの着信の場合、From パラメータは、client:tommy となります。
To 発信先の電話番号またはクライアント識別子です。 電話番号は「+」希望に続き国コードが続く形式で指定します。 (例: +16175551212) E.164形式と呼ばれます。 クライアント識別子は client: URIスキームから始まります。 たとえば「joey」というクライアント名に通話を発信するには、Toパラメーターの値はclient:joeyとなります。
ApiVersion この通話の処理に使用する Twilio API のバージョンです。 着信通話では、宛先の電話番号に設定された API バージョンになります。 発信通話では、発信通話の REST API リクエストで使用する API のバージョンになります。
Outgoing .parameters


パラメーター 概要
CallSid Twilio が生成したこの通話のユニークな識別子です。


The following methods have been deprecated and will be removed in a future release of twilio.js. Calling these methods will generate a deprecation warning unless the warnings parameter is set to false when calling Twilio.Device.setup().





Handler methods

Additionally, Twilio Client is moving toward the standard EventEmitter interface, meaning events should be managed with .on(eventName, handler) and .removeListener(eventName, handler), replacing our legacy handlers (such as .accept(handler), .error(handler), etc...). The following methods are deprecated:


These have been replaced with the following EventEmitter events:

Connection.on('accept', handler)
Connection.on('cancel', handler)
Connection.on('disconnect', handler)
Connection.on('error', handler)
Connection.on('mute', handler)
Connection.on('reject', handler)
Connection.on('volume', handler)

Note that there is no ignore event. The .ignore(handler) method is actually a backward-compatible listener for the .on('cancel', handler) event.

Rate this page:


誰しもが一度は考える「コーディングって難しい」。そんな時は、お問い合わせフォームから質問してください。 または、Stack Overflow でTwilioタグのついた情報から欲しいものを探してみましょう。