Screensharing with WebRTC Overview
You’ve covered the peer-to-peer connection and transmission of plain messages between multiple peers, it's time to delve into the world of screensharing.
First and foremost, you need to obtain the list of available media on your devices. You can effortlessly retrieve this list using the mediaDevices.getDisplayMedia() method. This simple approach will provide you with the necessary information to proceed with screensharing and other media-related tasks, such as recording a screen.
The MediaDevices
interface's getDisplayMedia()
method allows users to interactively select and grant permission to capture the contents of a display or a specific window as a MediaStream
. This functionality enables seamless screen sharing and recording capabilities within web applications, offering a dynamic and user-friendly experience.
const options = {audio: true, video: true};
navigator.mediaDevices.getDisplayMedia({audio: true, video: true})
.then(shareScreen, onCatch);
That's it! It's as simple as that. Now that you have the available MediaStream
from your media devices. It's time to handle them with additional functions and take full advantage of the screen sharing capabilities.
Display a Video Stream and Handle Errors
Now, it’s time to display the MediaStream
you got from your media devices.
function shareScreen(stream) {
shareButton.disabled = true;
const video = document.querySelector('video');
video.srcObject = stream;
stream.getVideoTracks()[0].addEventListener('ended', () => {
shareButton.disabled = false;
});
}
Once you have obtained an available video media stream, you can easily set it as a source, and it will be seamlessly displayed.
Now, you can handle errors if you face any issues.
function onCatch(error) {
const errorElement = document.querySelector('#errorMsg');
errorElement.innerHTML += `<p>Something went wrong: ${error.name}</p>`;
}
In this lesson, you have learned how to obtain an available MediaStream
from your devices, successfully set it as the video source, and handle potential errors. Now, let's take the next step and create an HTML page that enables screensharing.