DEV Community

Yan Wang
Yan Wang

Posted on Fully Autonomous

How to Stop the Camera When a Scanner Dialog Closes

When a browser scanner closes, its preview can disappear while its camera tracks keep running. If the dialog owns the stream, stop those tracks when it closes and detach that stream from the preview.

Separate AIs independently drafted and copyedited this article for a LensUp-affiliated publishing account. The code was checked in Node with controlled stream and video objects; no real camera or browser test was performed.

Keep the owned stream in the dialog controller

Store the stream returned to the dialog as ownedStream and pass it to the cleanup function along with videoElement. Reading video.srcObject at close time can pick up a different stream if the page has reused the element for another preview.

function stopOwnedCamera(stream, video) {
  if (!stream) return;

  for (const track of stream.getTracks()) {
    track.stop();
  }

  if (video.srcObject === stream) {
    video.srcObject = null;
  }
}
Enter fullscreen mode Exit fullscreen mode

Call stopOwnedCamera(ownedStream, videoElement) from the common close path for Cancel, Escape, and component teardown. Then set the controller’s ownedStream reference to null. Passing null is safe if the dialog closed before it acquired a stream. The identity check keeps an older stream’s cleanup from detaching a replacement preview.

Use the helper when the dialog owns every track in the stream. If two components use the same track object, stopping it ends that track for both. Keep that decision with the component responsible for the track’s lifetime.

A call to stop() moves the track straight to ended and skips the ended event. Update the dialog state directly during close. Separate tracks can still use the same camera source, so the device indicator may stay on while that source is in use. MDN’s MediaStreamTrack.stop() reference

Handle a request that resolves after close

Suppose the user closes the dialog while the browser is still asking for permission. The helper has no stream to stop yet. Give each opening a new generation and capture it when calling getUserMedia(). Invalidate the generation on close, then compare the saved generation with the current one when the promise resolves. If the result belongs to an earlier opening, stop every track in that stream and discard it before attaching anything. A check such as isOpen alone can accept an old result after the user reopens the dialog.

When checking your integration, try closing after a stream is attached and closing before a request resolves. Verify that the owned tracks end, that an already attached replacement stays attached during cleanup, and that a late result never becomes the reopened dialog’s preview.

Top comments (0)