how can I replace the getUserMedia function in Mozilla?

I have access to the camera using getUserMedia(), But it only works locally.

I understand that it doesn't work on a web server due to a security issue. So how can I replace getUserMedia() ?

 async function init() {
        try {
          // console.log("try");
          const stream = await navigator.mediaDevices.getUserMedia(constraints);
          handleSuccess(stream);
        } catch (e) {
          // console.log("catch");
          // console.log(e.name + ": " + e.message);
          errorMsgElement.innerHTML = `navigator.getUserMedia error:${e.toString()}`;
          //errorMsgElement.innerHTML = e.toString();
        }
      }

      // Success
      function handleSuccess(stream) {
        window.stream = stream;
        video.srcObject = stream;
      }


      // Load init
      init();

Upvotes: -1

Views: 469

Answers (3)

Clepsyd
Clepsyd

Reputation: 551

As others said, you need to enable HTTPS on your server if you don't run it locally. The getUserMedia() feature is THE way to get the video stream on a browser, and it works that way because access to the user's mic and webcam needs to be secure.

getUserMedia() is a powerful feature which can only be used in secure contexts; in insecure contexts, navigator.mediaDevices is undefined, preventing access to getUserMedia(). A secure context is, in short, a page loaded using HTTPS or the file:/// URL scheme, or a page loaded from localhost.

found in the docs here: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia

Maybe adding information on how your app is deployed, and what kind of app it is could help, but if it's a single page app, I can recommend this buildpack with heroku: https://elements.heroku.com/buildpacks/heroku/heroku-buildpack-static

The configuration is one JSON file, real simple, and lets you enable HTTPS.

Upvotes: 0

O. Jones
O. Jones

Reputation: 108641

getUserMedia() works correctly when you use it from Javascript served via https. As you have discovered, it doesn't work at all when you don't use https.

Setting up your local development environment to use https is a notorious pain in the neck. It's dependent on OS of your development machine and on the browser (Firefox) you use. But, still, you must do it. https://www.freecodecamp.org/news/how-to-get-https-working-on-your-local-development-environment-in-5-minutes-7af615770eec/

Upvotes: 0

Brad
Brad

Reputation: 163291

All you need to do is get a proper HTTPS certificate running on your server. Once you've done that, you'll be up and running.

You can't "replace the function" to get it working otherwise.

Upvotes: 0

Related Questions