How To Do Screen Sharing In JavaScript

In this article, we are going to examine the way to use the Screen Capture API and its getDisplayMedia() technique to capture half or all of a screensharing throughout a WebRTC conference session.

<!DOCTYPE html>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Screen Sharing</title>
  <div style="width:80%;background: grey;margin: auto;">
    <video id="video" autoplay playsinline muted></video>
  <div style="width:80%;margin: auto;padding-top:10px ;">
  <button id="start"> Start Screen Sharing</button>
  <button id="stop"> Stop</button>
  <script type="text/javascript">
    const videoElem = document.getElementById("video");
    const startElem = document.getElementById("start");
    const stopElem = document.getElementById("stop");

      // Options for getDisplayMedia()

      var displayMediaOptions = {
        video: {
          cursor: "always",
        audio: false

      // Set event listeners for the start and stop buttons
      startElem.addEventListener("click", function(evt) {
      }, false);

      stopElem.addEventListener("click", function(evt) {
      }, false);
      async function startCapture() {

        try {
          videoElem.srcObject = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
        } catch(err) {
          console.error("Error: " + err);
      function stopCapture(evt) {
        let tracks = videoElem.srcObject.getTracks();

        tracks.forEach(track => track.stop());
        videoElem.srcObject = null;
      function dumpOptionsInfo() {
        const videoTrack = videoElem.srcObject.getVideoTracks()[0];"Track settings:");, null, 2));"Track constraints:");, null, 2));

Code in action:


Submit a Comment

Your email address will not be published.


Select Categories