Search code examples
vue.jsnuxt.jsgetusermedia

navigator.mediaDevices.getUserMedia - UNDEFINED in Nuxt


I have the following code which is to trigger the camera in Nuxt so I can capture an image, but I keep getting an error saying:

Cannot read properties of undefined (reading 'getUserMedia')

navigator.mediaDevices.getUserMedia(constraints).then((stream) => {
  player.srcObject = stream;
});

This is in a method. I don't have anything in mounted.

Can anyone please help me out?


Solution

  • Thanks to @kissun for pointing me in the right direction.

    I reckon this is a recurring issue because one cannot use navigator.mediaDevices.getUserMedia in dev mode.

    I added this function in mounted as suggested, however that did not work either.

    After searching online, I discovered I had to use HTTPS in dev mode for it to ultimately work.

    To do that, create your HTTPS certificate and key first, and then configure nuxt. Original, full, instructions can be found here How to run NUXT (npm run dev) with HTTPS in localhost?

    enter image description here

    To setup nuxt, add this into your server object, in your nuxt.config.js file:

    import path from 'path'
    import fs from 'fs'
    
      server: {
        https: {
          key: fs.readFileSync(path.resolve(__dirname, 'server.key')),
          cert: fs.readFileSync(path.resolve(__dirname, 'server.crt'))
        }
      }
    

    Now try using navigator.mediaDevices.getUserMedia