2
votes

I'm using Twilio JS SDK quickstart to make and receive calls on my website: https://www.twilio.com/docs/voice/client/javascript/quickstart

https://www.twilio.com/docs/voice/client/javascript/connection

When I receive a phone call I want to connect to that incoming call by clicking a button, so this is my code:

HTML:

<div id="register"></div>

JS:

function capable(tkn){ //tkn is the token.
 var devices;
 devices = new Twilio.Device(tkn, {
  // Set Opus as our preferred codec. Opus generally performs better, requiring less bandwidth and
  // providing better audio quality in restrained network conditions. Opus will be default in 2.0.
  allowIncomingWhileBusy: true,
  codecPreferences: ['opus', 'pcmu'],
  // Use fake DTMF tones client-side. Real tones are still sent to the other end of the call,
  // but the client-side DTMF tones are fake. This prevents the local mic capturing the DTMF tone
  // a second time and sending the tone twice. This will be default in 2.0.
  fakeLocalDTMF: true,
  sounds: {
    incoming: 'https://www.mywebsite.com/audio/ring-ring.mp3'
  }

 });

 devices.on('incoming', function (conn) {
   console.log('Incoming connection from ' + conn.parameters.From);
   var telf = conn.parameters.From;
   var reg = '<div class="reg_item">';
   reg += '<p>Caller: </p>' + telf;
   reg += '<button onclick="answerB('+conn+');" class="btn btn-md btn-success"><i class="fa fa-phone" aria-hidden="true"></i></button>';
   reg += '</div>';

   $("#register").prepend(reg);
 }

}

function answerB(idx){
  console.log(idx);
  idx.accept();
}

It seems it doesn't work in that way showing this error:

enter image description here

Console:

enter image description here

How can I fix it?

I'd like your help.

Thank you.

1

1 Answers

2
votes

Instead of this:

console.log('Incoming connection from ' + conn.parameters.From);
var telf = conn.parameters.From;
var reg = '<div class="reg_item">';
reg += '<p>Caller: </p>' + telf;
reg += '<button onclick="answerB(' + conn + ');" class="btn btn-md btn-success"><i class="fa fa-phone" aria-hidden="true"></i></button>';
reg += '</div>';

$("#register").prepend(reg);

change to this:

console.log('Incoming connection from ' + conn.parameters.From);
var telf = conn.parameters.From;
var reg = '<div class="reg_item">';
reg += '<p>Caller: </p>' + telf;
reg += '<button id="button-answer" class="btn btn-md btn-success"><i class="fa fa-phone" aria-hidden="true"></i></button>';
reg += '</div>';

$("#register").prepend(reg);
$("#button-answer").on("click", conn, answerB);

and your answerB function should be:

function answerB(event) {
    console.log(event.data);
    event.data.accept();
}

Let me know if you managed to get it working.