Alexandr Stupak
Alexandr Stupak

Reputation: 65

navigator.getUserMedia function is undefined

Navigator.getUserMedia()

Can the navigator.getUserMedia function be undefined because the camera or access to the microphone is not granted access?

Upvotes: 2

Views: 2723

Answers (2)

Ahmad Alhilal
Ahmad Alhilal

Reputation: 454

Firstly, make sure you use navigator.mediaDevices.getUserMedia() instead of navigator.getUserMedia(). The latter is deprecated.

Secondly, grabbing navigator.mediaDevices.getUserMedia() on Chrome requires a secure context.
If the server is js-based, then you need to use https which then be used to access home page (e.g., index.html) instead of http. https connection requires creating/using credentials (i.e., certificate and private key). The following code is given for the sake of demonstration:

// change key and cert if you have other ones you use with a different name
var fs = require('fs');
var https = require('https');
var privateKey  = fs.readFileSync('webrtcwwsocket-key.pem', 'utf8');
var certificate = fs.readFileSync('webrtcwwsocket-cert.pem', 'utf8');
var credentials = {key: privateKey, cert: certificate};
const express = require('express')
const app = express()
const httpsServer = https.createServer(credentials, app)

If you are using python-based server, then you need to create ssl context as follows:

ssl_context = ssl.SSLContext()
ssl_context.load_cert_chain(cert_file_path, key_file_path)

Upvotes: 0

Tamas Szoke
Tamas Szoke

Reputation: 5542

From the documentation:

This is a legacy method. Please use the newer navigator.mediaDevices.getUserMedia() instead.

For example:

async function getMedia(constraints) {
  let stream = null;

  try {
    stream = await navigator.mediaDevices.getUserMedia(constraints);
    console.log('1')
    /* use the stream */
  } catch (err) {
    /* handle the error */
  }
}

getMedia({audio: true, video: true})

Source: MediaDevices documentation.

Upvotes: 2

Related Questions