SharePoint Add-in: Accessing Webcam with Only Javascript
This blog post details how to access your Webcam via Javascript through the browser, and upload that content to a SharePoint library. Then, with an added bonus, set it to be your User Profile Picture.
I have build this User Profile Webcam solution as an Add-in for SharePoint (was App for SharePoint). This is a SharePoint Hosted app. All the code runs in the browser and access SharePoint via the SharePoint Online API.
Step 1. Access your webcam.
Modern Browsers: Immersive Internet Explorer, Firefox, Chrome and Safari all has ways to access your webcam via
getUserMedia
But this doesn't work on IE (Desktop). So for that we'll add a Polyfill (Flash).
There's a project on github that does this nicely, and I use large chunks of the code from their demo.
The code basically takes either the webrtc object and copy the image to the App canvas. Or use the flash polyfill and Flash will write the image to the canvas element.
Step 2. Binary Format
This part is hairy. But you are a developer, and dealing with Binary Encoding in JavaScript is what we do.
This is base64 dataUrl format.
This gives us ByteArray. We're getting close.
I'd like to tell you that I spend a good 3 evenings working to this point. Try debugging that code and see if your eyes bleed!
SharePoint API wants data in BinaryString format. Which is basically each byte of the ByteArray encoded as a concatenated string.
Step 3. Upload to SharePoint
Step 4. Setting User Profile Picture.
For this API call to /setmyprofilepicture to succeed, your App must have additional permissions.
This will ask the user (or Tenant Administrator) to grant the correct permission.
If you don't grant this permission, the webcam can still save picture to library, but it won't be able to set picture as user profile picture.
Summary
- Get Webcam via Browser
- Process canvas data to imageUrl to byteArray to BinaryString
- Upload to SharePoint Library
- Set as User Profile Picture
- Achieve Zoolander face!
- You can download the App for free from the Office Store to see it in action.
Feel free as a developer to hit F12 and step through the code. - Leave a comment below and let me know what you think. For example, I think there's a need for an Outlook Add-in that uses the webcam. Especially, if it can run on an iPad.