Home > Mobile >  Why do I have an error "TypeError: Cannot read properties of null (reading 'getTracks'
Why do I have an error "TypeError: Cannot read properties of null (reading 'getTracks'

Time:07-18

Here is my code :

            const videoElem = document.getElementById("videoScan");
            var stream = document.getElementById("videoScan").srcObject;
            var tracks = stream.getTracks();
            tracks.forEach(function (track) {
                track.stop();
            });
            videoElem.srcObject = null;

I am trying to stop all camera streams in order to make ZXing work. However, I have the following error (only on android tablet) :

enter image description here

Problem is, I can't solve it, but everything is working well. And when I do a try/catch, code stops working. I can't figure out why this error is displaying.

CodePudding user response:

When you say "everything is working well", you mean that you get what you want as output?

If the code throwing the error is the same you are showing us, then it means that streams contains null.

Since streams is a const value (thus once only) assigned on the previous instructions, it means that document.getElementById("videoScan").srcObject is null too.

I'd suggest you to do some other debug by, i.e., printing out to JS console (if you have access to it from your Android debug environment, I'm sure there's a way) what's inside stream, before trying to access its getTracks method reference.

Please do also check the compatibility with srcObject with your Android (browser?) environment: MDN has a compatibility list you can inspect.

CodePudding user response:

The simplest way to catch this null reference error, is to check if tracks actually exists.

const videoElem = document.getElementById("videoScan");
const stream = videoElem.srcObject;

if (stream && stream?.getTracks()) {
  const tracks = stream.getTracks();
  tracks.forEach(function (track) {
    track.stop();
  });
} else {
  console.warn('Stream object is not available');
}

videoElem.srcObject = null;

CodePudding user response:

So I found the solution. The error stopped the code from continuing, which, in my case, actually made it work. I made a very basic mistake : not paying enough attention to the debug results. However, if anyone has the error "Uncaught (in promise) DOMException: Could not start video source" with ZXing on Android, you simply have to cut all video streams to allow chrome starting an other camera. It will not work otherwise.

  • Related