Issue with Camera and Mic Access in Embedded HTML within Iframe

I wanted to embed an HTML in which mic and camera access should be allowed. I noticed that the iframe wrapping my HTML did not allow camera and mic access.

I found a solution by adding custom code to the body end, which finds all the iframes within a page and grants camera and mic access. Everything works fine when I navigate to my page using the navigation menu, but when I open the link directly in a new tab, the camera and mic access is not granted.

Do you have any idea why this happens, or if there is another workaround for this issue that allows camera and mic access?

Hi, Ada_Sulejmani !! I have experienced that issue before. I also initially tried to allow it with custom code, but in conclusion, if you want to use media such as a camera or microphone, it’s better to implement it using custom elements rather than HTML components.

Do you maybe have a simple code example?

Hi, @capo !!

It had been a while for me as well, so I asked AI to help create a simple draft. :innocent: I’ve confirmed that it works for now. Please copy this code into a .js file and load it as an external script in the custom element you placed on the page. Be sure to set the tag name to “camera-view”. Since this is just a very basic draft, feel free to customize it further—add your own CSS for styling, or include a button to start the camera and microphone manually, for example. :innocent:

class CameraView extends HTMLElement {
    
    constructor() {
        super();
        this.attachShadow({ mode: 'open' }); // Shadow DOM
    }

    connectedCallback() {

        const video = document.createElement('video');
        video.autoplay = true;
        video.playsInline = true;
        this.shadowRoot.appendChild(video);

        navigator.mediaDevices.getUserMedia({ video: true, audio: true })
            .then((stream) => {
                video.srcObject = stream;
            })
            .catch((err) => {
                const errorMsg = document.createElement('p');
                errorMsg.textContent = 'Failed to access the camera and microphone: ' + err.message;
                this.shadowRoot.appendChild(errorMsg);
                console.error(err);
            });

    }

}

customElements.define('camera-view', CameraView);