Overview
In the previous lesson, you learned how to obtain a MediaStream
from your available devices. Now, let's take the next step and create an HTML page that empowers you to select the display you wish to share, along with some user interface components to facilitate the screensharing process.
Building a complete screen sharing interface requires careful integration of HTML structure, user interaction patterns, and WebRTC APIs. The interface must provide clear visual feedback about sharing status while maintaining simplicity for users who may not be familiar with technical concepts.
Screen sharing applications typically follow a predictable workflow: interface initialization, user-triggered capture request, display source selection, active sharing state, and termination handling. Each phase requires appropriate user interface elements and state management to create a smooth user experience.
First, create an index.html
HTML file that contains a screen sharing button.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=yes, initial-scale=1, maximum-scale=1">
<meta id="theme-color" name="theme-color" content="#ffffff">
<title>Screensharing</title>
<link rel="stylesheet" href="./css/main.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-blue.min.css">
<script defer src="https://code.getmdl.io/1.3.0/material.min.js"></script>
</head>
<body>
<div id="container">
<h4><a href="https://github.com/GetStream/webrtc-for-the-brave/tree/main/lesson01-4" title="WebRTC for The Brave">
Screensharing Sample</a> <span>getDisplayMedia</span>
</h4>
<video id="gum-local" autoplay playsinline muted></video>
<button class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent" id="shareButton"
disabled>Share Screen
</button>
<div id="errorMsg"></div>
</div>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
<script src="js/main.js"></script>
<script src="../../../js/lib/ga.js"></script>
</body>
</html>
The HTML structure demonstrates a clean, minimal interface focused on the core screen sharing functionality. The video element provides immediate visual feedback when screen sharing begins, while the single button creates a clear call-to-action for users.
The Material Design components enhance the interface with professional styling and interaction feedback. The disabled button state prevents users from attempting screen sharing before the page is fully loaded and API availability is confirmed.
The error message container provides a dedicated space for displaying permission issues or browser compatibility problems, ensuring users receive clear feedback when screen sharing cannot be initiated.
Complete the screensharing
Having successfully created a screensharing page, it's now time to integrate the HTML page with the necessary scripts for screensharing. To get started, add an event listener for the start button as shown below:
'use strict';
const shareButton = document.getElementById('shareButton');
shareButton.addEventListener('click', () => {
navigator.mediaDevices.getDisplayMedia({audio: true, video: true})
.then(shareScreen, onCatch);
});
The event listener implementation demonstrates the modern JavaScript pattern for handling user interactions that trigger asynchronous WebRTC operations. The getDisplayMedia call initiates the browser's native screen selection interface, providing users with granular control over what content they share.
The audio and video constraints enable capture of both visual content and system audio, providing comprehensive screen sharing capabilities. This configuration works well for most use cases, though applications can adjust constraints based on specific requirements.
As you can see the above code, you can add an event listener to detect click event from user and handle them with the shareScreen
and onCatch
functions.
Now let's complete the shareScreen
and onCatch
functions to set video source and handle error cases.
function shareScreen(stream) {
shareButton.disabled = true;
const video = document.querySelector('video');
video.srcObject = stream;
stream.getVideoTracks()[0].addEventListener('ended', () => {
shareButton.disabled = false;
});
}
// Function to handle errors during media stream acquisition
function onCatch(error) {
const errorElement = document.querySelector('#errorMsg');
errorElement.innerHTML += `<p>Something went wrong: ${error.name}</p>`;
}
if ((navigator.mediaDevices && 'getDisplayMedia' in navigator.mediaDevices)) {
shareButton.disabled = false;
}
The shareScreen function handles successful stream acquisition by immediately displaying the captured content and updating interface state. Disabling the share button prevents multiple simultaneous sharing sessions while providing clear visual feedback about current status.
The ended event listener provides crucial lifecycle management, automatically re-enabling the share button when users terminate sharing through browser controls or when shared applications close. This ensures the interface stays synchronized with actual sharing state.
The feature detection logic ensures the share button is only enabled when getDisplayMedia is available, preventing user frustration with unsupported browsers. This progressive enhancement pattern provides appropriate fallbacks for different browser capabilities.
Error handling covers common failure scenarios including permission denial, invalid source selection, and system-level restrictions. Clear error messages help users understand issues and take appropriate action.
As demonstrated in the example above, once you have selected an available media stream, it will be set as the video source.
Additionally, by incorporating an ended
event listener to the video track, you can effectively detect whether the screensharing session was terminated by the user or not.
The ended event detection is particularly important because screen sharing can terminate through various mechanisms beyond application control. Users might close shared windows, revoke permissions through browser interfaces, or encounter system-level interruptions that automatically stop sharing.
Proper event handling enables applications to respond gracefully to these scenarios, updating their interface state and potentially offering users options to restart sharing or switch to alternative content sources.
Running the WebRTC demo application
Now it's time to run the demo application. If you execute the index.html
file, you will see the demo below:
The interactive demonstration provides hands-on experience with the complete screen sharing workflow, from initial page load through source selection to active sharing. The demo environment enables experimentation with different sharing scenarios and browser behaviors.
If you click the Share Screen button, you'll able to see the window selector that allows you to choose which screen should be sharing:
The browser's native source selection interface provides users with comprehensive options for choosing shared content. Users can select entire screens for full desktop sharing, specific application windows for focused collaboration, or individual browser tabs for web-based content sharing.
The selection interface includes privacy controls and permission settings that ensure users understand the scope of shared content. This native interface maintains consistent behavior across different websites while providing appropriate security protections.
Next, if you click the Share button on the window, your screen will be shared as shown below:
The successful screen sharing display demonstrates the complete capture and rendering pipeline working correctly. The video element shows the captured content in real-time, providing immediate confirmation that sharing is active and displaying the content other participants would see.
The visual feedback helps users verify they've selected the correct content source and that sensitive information isn't inadvertently shared. This preview capability is essential for building user confidence in screen sharing functionality.
This tutorial concludes how to share your screens with available options.
The foundation established here enables integration with peer-to-peer communication systems, where captured screen content can be transmitted to remote participants through WebRTC connections. The MediaStream generated by getDisplayMedia integrates seamlessly with existing peer connection infrastructure.
Note: You can demonstrate and test the sample application about Screensharing on your web browser without building the project.