From d688d2f3029c3e18be160242c20fafcaf28fdaf6 Mon Sep 17 00:00:00 2001 From: Alexandre Danault Date: Mon, 9 Aug 2021 14:01:10 -0400 Subject: [PATCH] Unload camera even when then component il unloaded before preview is shown --- src/index.js | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/index.js b/src/index.js index 1a0639c..6929d0e 100644 --- a/src/index.js +++ b/src/index.js @@ -120,6 +120,8 @@ module.exports = class Reader extends Component { this.clearComponent() } clearComponent() { + // Flag stream to stop + this.shouldStop = true // Remove all event listeners and variables if (this.timeout) { clearTimeout(this.timeout) @@ -143,8 +145,9 @@ module.exports = class Reader extends Component { const isFirefox = /firefox/i.test(navigator.userAgent); const isSafari = !!navigator.userAgent.match(/Version\/[\d/]+.*Safari/); + let supported = {} if (navigator.mediaDevices && typeof navigator.mediaDevices.getSupportedConstraints === 'function') { - const supported = navigator.mediaDevices.getSupportedConstraints() + supported = navigator.mediaDevices.getSupportedConstraints() } const constraints = {} @@ -172,6 +175,14 @@ module.exports = class Reader extends Component { const { preview } = this.els const { facingMode } = this.props + // Stop stream if we've been asked to + if (this.shouldStop) { + const streamTrackToStop = stream.getTracks()[0] + setTimeout(() => { + streamTrackToStop.stop(); + }, 2000); + } + // Preview element hasn't been rendered so wait for it. if (!preview) { return setTimeout(this.handleVideo, 200, stream)