Sharing Screens with the New Javascript Screen Capture API
📣 Sponsor
Post Covid-19, the world is becoming increasingly more and more remotely based. Although common before, the phrase "let me share my screen.." has become standard vernacular in the business world. As such, there is an increasing need for services like screen sharing within the web platform.
To solve this, the new Javascript Screen Capture API lets users give permission to a website to capture their screen. After permission is granted, we can use that data in web applications. An example might be, that we send this data live to another user as part of a screen sharing application.
How does it work?
A straightforward example of how this works is shown below.
let captureVideo = async function() {
try {
let getScreenData = await navigator.mediaDevices.getDisplayMedia({
video: true,
audio: true
});
videoElement.srcObject = getScreenData;
} catch (e) {
console.log(e);
}
}
We then have some HTML that looks like this. Note, it's important your video element is autoplaying or set to play:
<video id="my-video-stream" autoplay></video>
The getDisplayMedia
function only takes two options, and that is whether it should access video or audio, or both. We use await
here, because we need to wait for the user to us give access to their screen.
After we give access, all data is accessible via the getScreenData variable we defined. The type of data this returns is a MediaStream which is a bespoke type used for web based media streaming.
Demo
To make this come to life, I've used the code above to make a simple demo which starts when you click the button below. Note: if this doesn't work, your browser may not be supported! This currently works on most desktop browsers, and very few mobile browsers. Scroll down for the support table for more information.
Support
As with most new specifications, this is not a functionality supported by all browsers, although support may be greater than you think. Essentially all desktop browsers support this, which typically is the device we share screens on. See below for browsers which currently support this functionality.
More Tips and Tricks for Javascript
- Javascript: Check if an Array is a Subset of Another Array
- Javascript Objects Cheatsheet
- Asynchronous Operations in Javascript
- Waiting for the DOM to be ready in Javascript
- How fetch works in Javascript
- Generating a Sitemap with Node.JS and Javascript Automatically
- How Generator Functions work in Javascript
- Javascript toLowerCase() - Convert Strings to Lowercase
- Javascript Dates and How they Work
- How does the Javascript logical OR (||) operator work?