Permissions policy violation in Chrome-based browsers while accessing camera

643 views Asked by At

I'm encountering a permissions policy violation issue specific to Chrome-based browsers when attempting to access the camera using the following code. Strangely, the code works without any errors in Safari and Firefox. The error message I'm receiving is:

[Violation] Permissions policy violation: camera is not allowed in this document. Error accessing the camera: DOMException: Permission denied

Here's the relevant code snippet:

const scanner = document.getElementById('scanner');
const qrCanvas = document.getElementById('qr-canvas');
const qrDataElement = document.getElementById('qr-data');
const scanMenuItemCamera = document.getElementById('scan');
const menuItemsCamera = document.querySelectorAll('.menu-item');
let cameraStream = null;

function startCameraFeed() {
  if (scanner && qrCanvas) {
    const videoConstraints = {
      facingMode: 'environment',
      width: 1280,
      height: 720
    };

    if (window.location.protocol === 'https:') {
      navigator.mediaDevices.getUserMedia({
          video: videoConstraints
        })
        .then(stream => {
          scanner.srcObject = stream;
          scanner.addEventListener('play', scanCodes);
          cameraStream = stream;

          const videoElement = document.getElementById('scanner');
          const zoomSlider = document.getElementById('zoomSlider');

          zoomSlider.addEventListener('input', (event) => {
            const scale = parseFloat(event.target.value);
            videoElement.style.transform = `scale(${scale})`;
          });

          videoElement.style.transform = 'translateZ(0)';
        })
        .catch(error => console.error('Error accessing the camera:', error));
    } else {
      console.error('Please use a secure connection (HTTPS) to access the camera.');
    }
  }
}

document.addEventListener('DOMContentLoaded', () => {
  startCameraFeed();

  menuItemsCamera.forEach(menuItemCamera => {
    menuItemCamera.addEventListener('click', () => {
      if (menuItemCamera.id === 'scan') {
        startCameraFeed();
      } else {
        stopCameraFeed();
      }
    });
  });

  function stopCameraFeed() {
    if (cameraStream) {
      cameraStream.getTracks().forEach(track => track.stop());
      cameraStream = null;
    }
  }

  scanMenuItemCamera.addEventListener('click', startCameraFeed);
});
<div id="controls">
  <input type="range" id="zoomSlider" min="1" max="5" step="0.01" value="1">
</div>


<video id="scanner" autoplay=""></video>
<canvas id="qr-canvas"></canvas>
<div id="qr-data" class="background"></div>

<a class="menu-item" id="scan"></a>

0

There are 0 answers