RTCPeerConnection.createAnswer callback returns undefined object in mozilla for WebRTC chat

一曲冷凌霜 提交于 2019-11-28 09:29:02

问题


Following is my code to answer the incoming call:

var pc = connection.pc;
pc.setRemoteDescription(sdp,function() {
 pc.createAnswer(function(answer) {
  pc.setLocalDescription(answer,function() {
   // code for sending the answer
 }) 
 })
})

The above code works fine for chrome, but when i run the same in mozilla, the answer obtained from pc.createAnswer callback is undefined. As a result of which it gives me following error:

TypeError: Argument 1 of RTCPeerConnection.setLocalDescription is not an object.


回答1:


The problem is you're not checking errors, specifically: not passing in the required error callbacks.

setRemoteDescription and setRemoteDescription require either three arguments (legacy callback style) or one (promises), but you're passing in two. Same for createAnswer minus one.

The browser's JS bindings end up picking the wrong overload, returning you a promise which you're not checking either, effectively swallowing errors.

Either add the necessary error callbacks:

var pc = connection.pc;
pc.setRemoteDescription(sdp, function() {
  pc.createAnswer(function(answer) {
    pc.setLocalDescription(answer, function() {
      // code for sending the answer
    }, function(e) {
      console.error(e);
    });
  }, function(e) {
    console.error(e);
  });
}, function(e) {
  console.error(e);
});

Or use the modern promise API:

var pc = connection.pc;
pc.setRemoteDescription(sdp)
  .then(() => pc.createAnswer())
  .then(answer => pc.setLocalDescription(answer))
  .then(() => {
    // code for sending the answer
  })
  .catch(e => console.error(e));

The promise API is available natively in Firefox, or through adapter.js in Chrome. See fiddle.

And always check for errors. ;)



来源:https://stackoverflow.com/questions/36400078/rtcpeerconnection-createanswer-callback-returns-undefined-object-in-mozilla-for

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!