All articles

Understanding WebRTC Screen Sharing with JavaScript: A Simple Guide

If you're new to coding or just curious about how screen sharing works with JavaScript, this guide breaks it down, from the getDisplayMedia API to a complete peer-connection setup, plus the gotchas that trip people up in production.

Muhammad Aamir8 min readJul 22, 2024
Illustration of WebRTC screen sharing implemented with JavaScript

WebRTC, short for Web Real-Time Communication, is designed to enable web browsers to communicate instantly with each other using straightforward APIs. It's the same stack that powers most modern collaboration features in the web apps we build.

It facilitates peer-to-peer communication on web pages and improves applications with features like video conferencing and file sharing. Screen sharing has become an essential feature for online meetings, remote support, and collaborative work, and WebRTC makes it possible directly in your browser, without configuring complex server systems.

How Does Screen Sharing Work?

Screen sharing involves capturing your computer screen and sending it to another user. WebRTC makes this process smooth and efficient, it's a key feature of WebRTC that lets users share their screens during video calls or streaming.

JavaScript
async function startScreenSharing() {
    try {
        const screenStream = await navigator.mediaDevices.getDisplayMedia({ video: true });
        // Handle the captured stream
    } catch (error) {
        console.error('Error: Unable to access display media.', error);
    }
}

Ensuring Browser Compatibility and HTTPS for WebRTC

WebRTC support across browsers can differ, so developers must consider each browser's compatibility with features like getDisplayMedia(). For successful screen-sharing implementation:

  • Use HTTPS: Ensure your server supports SSL/TLS for secure browsing.

  • Use WSS: Use secure WebSocket signalling for WebRTC connections.

  • Check browser compatibility: Test your application across different browsers to confirm functionality.

A Complete Guide on Implementing Screen Sharing

Screen sharing is a powerful feature in web applications, allowing users to share their screen content in real time. Here's a step-by-step guide to implementing screen sharing using WebRTC:

1. Initialise the peer connection

Create an RTCPeerConnection to manage audio and video streams.

JavaScript
const peerConnection = new RTCPeerConnection(configuration);

2. Capture the screen

Use the getDisplayMedia() method to get a video stream of the user's screen. This API, part of the MediaDevices interface, is essential for acquiring a media stream that captures the screen's content.

JavaScript
async function captureScreen() {
    const displayMediaOptions = {
        video: {
            cursor: "always"
        },
        audio: false
    };
    return await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
}

3. Add the screen stream

Add the captured video stream to the peer connection.

JavaScript
const stream = await captureScreen();
stream.getTracks().forEach(track => {
    peerConnection.addTrack(track, stream);
});

4. Handle offers and answers

Set up signalling to exchange connection offers and answers between peers, exchanging SDP (Session Description Protocol) proposals and responses.

JavaScript
peerConnection.onicecandidate = event => {
    if (event.candidate) {
        sendCandidateToPeer(event.candidate);
    }
};

async function createAndSendOffer() {
    const offer = await peerConnection.createOffer();
    await peerConnection.setLocalDescription(offer);
    sendOfferToPeer(offer);
}

5. Manage the stream

Finish the connection setup by handling signalling data (ICE candidates and remote descriptions) and provide options to start and stop screen sharing.

Advanced Features

1. Support multiple participants

Enable several users to view the shared screen at once for meetings or group work. Manage this by creating multiple peer connections or using a server to broadcast the stream.

2. Create private rooms

Allow users to set up private rooms where only invited participants can view the screen. Use unique room links or tokens for access and ensure secure link sharing.

3. Adjust video quality

Optimise video quality based on network speed. Use settings to adjust resolution and frame rate, ensuring smooth performance whether you need high detail or lower bandwidth usage.

4. Implementation

Set video quality by using getDisplayMedia() to control resolution, frame rate, and other parameters. Adjust these for high-definition or lower quality based on network speed.

JavaScript
const highQualityOptions = {
    video: {
        width: { ideal: 1920 },
        height: { ideal: 1080 },
        frameRate: { ideal: 30 }
    }
};

const lowQualityOptions = {
    video: {
        width: { ideal: 640 },
        height: { ideal: 480 },
        frameRate: { ideal: 15 }
    }
};

async function captureScreen(qualityOptions) {
    return await navigator.mediaDevices.getDisplayMedia(qualityOptions);
}

Handling Screen Sharing Issues with WebRTC

WebRTC screen sharing can present challenges like browser compatibility, network constraints, and API limitations. Common issues and solutions:

Permission Denied error

When implementing screen sharing with WebRTC, users might encounter a Permission Denied error if they deny access. To handle this, ensure your permission prompt is clear and polite, and gracefully manage errors by informing users and guiding them on granting access.

Black screen or no content

A black screen or missing content usually indicates that the user hasn't selected the correct screen or window, or there may be browser issues. Confirm that the browser supports screen sharing and is updated, some sites or apps might block this feature.

Lag, quality, and compatibility issues

For lag or poor quality, ensure both sender and receiver have stable internet connections and optimise quality settings. Address browser compatibility issues by testing across different browsers and recommending updates. If connection problems arise, check your signalling implementation to ensure proper exchange of offer, answer, and ICE candidates between peers.

Conclusion

WebRTC makes screen sharing easy and effective directly from your browser. This guide covered the key steps, setting up peer connections, capturing your screen, and managing the stream. By ensuring browser compatibility, using HTTPS, and configuring media settings carefully, you can create a smooth screen-sharing experience. Advanced features like multiple participants, private rooms, and video quality adjustments further enhance your application. Address common issues like permission errors and lag to keep the user experience seamless. With these practices, you can leverage WebRTC to improve real-time communication in your web applications. For a deeper look at the moving parts of the underlying stack, see how WebRTC protocols work together.

Tags
  • WebRTC
  • JavaScript
  • Screen Sharing
  • getDisplayMedia
  • Tutorial
  • Web Development