[英]Why do I have an error "TypeError: Cannot read properties of null (reading 'getTracks')", but the code is working?
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.我正在尝试停止所有摄像机流以使 ZXing 正常工作。 However, I have the following error ( only on android tablet ) :但是,我有以下错误(仅在 android 平板电脑上):
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.我无法弄清楚为什么会显示此错误。
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
.如果抛出错误的代码与您向我们展示的代码相同,则表示streams
包含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.由于streams
是在前面的指令中分配的const
值(因此只有一次),这意味着document.getElementById("videoScan").srcObject
也为空。
I'd suggest you to do some other debug by, ie, 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.我建议你做一些其他调试,即打印到 JS 控制台(如果你可以从你的 Android 调试环境访问它,我敢肯定有办法)在尝试访问它的getTracks
之前, stream
里面有什么方法参考。
Please do also check the compatibility with srcObject
with your Android (browser?) environment: MDN has a compatibility list you can inspect.请同时检查srcObject
与您的 Android(浏览器?)环境的兼容性:MDN 有一个您可以检查的兼容性列表。
The simplest way to catch this null reference error, is to check if tracks
actually exists.捕获此空引用错误的最简单方法是检查tracks
是否确实存在。
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;
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.但是,如果有人在 Android 上使用 ZXing 出现错误“ Uncaught (in promise) DOMException: Could not start video source ”,您只需剪切所有视频流以允许 chrome 启动其他相机。 It will not work otherwise.否则它将无法正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.