Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access webcam in a chrome extension

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.

like image 564
giladbach Avatar asked Oct 21 '25 18:10

giladbach


1 Answers

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.

like image 193
giladbach Avatar answered Oct 24 '25 09:10

giladbach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!