How to access webcam in a chrome extension
Asked Answered
L

1

4

How can I access the webcam from my chrome extension? Whenever I try to access the camera from a regular html file it seems to be working fine but when I use the same code in my extension it doesn't work.

Longhand answered 19/10, 2022 at 22:22 Comment(3)
Hello! Could you edit your question to be more question like? A good tip is to write your question like you're still looking for an answer, even though it's a canonical (you're posting an answer)Tayler
I am NOT voting to close because self answered questions are encouraged see: Can I answer my own question? Yes, it might have been written better and OP should update to make the question clear.Cyb
@SterlingArcher rewrote it as a question, thanks.Longhand
L
5

In order to be able to access the webcam you need to get permission which you cannot do from the contents.js, but what you can do is create a button in the options page which requests the permission.

Here are the steps:

1) Create an options.html file and add a reference to the manifest.json like this: "options_page": "options.html"

2) Create an options.js file, link it in the options.html file and add a button that will trigger the request for webcam access by adding the following lines:

<button id="requestPermission">Click for permission prompt</button>
<script src="options.js"></script>

Inside the options.js file add the following lines:

let button = document.getElementById('requestPermission');

button.onclick = ()=>{
    console.log('ya');
    navigator.getUserMedia = navigator.getUserMedia ||
                    navigator.webkitGetUserMedia ||
                    navigator.mozGetUserMedia;

    if (navigator.getUserMedia) {
    navigator.getUserMedia({ audio: false, video: { width: 1280, height: 720 } },
        (stream) => {
            console.log('success');
        },
        (err) => {
            console.error(`The following error occurred: ${err.name}`);
        }
    );
    } else {
        console.log("getUserMedia not supported");
    }
};

After following these steps you can right click your extension's icon and press options, this will open the options page where you can press the button and allow the extension to use the camera.

Longhand answered 19/10, 2022 at 23:1 Comment(1)
If it is not working for anybody its probably because navigator.getUserMedia has been deprecated you should access it like this navigator.mediaDevices.getUserMediaStanfordstang

© 2022 - 2025 — McMap. All rights reserved.