DEV Community

Cover image for How To Create a Screen Sharing Application With JavaScript
Anthony Smith
Anthony Smith

Posted on • Edited on

How To Create a Screen Sharing Application With JavaScript

Have you ever wondered how hard or easy it would be to create your own screen-sharing application?

In this article, we will show you how to create a screen-sharing application with JavaScript via the Screen Capture API
and its getDisplayMedia() technique. This will allow us to capture half or all of a screen and share it with other
users throughout a WebRTC conference session.

Initial Steps:

  1. Create a new project in your favorite IDE.
  2. Setup HTML boilerplate code
  3. Add JavaScript code
  4. Deploy Live server

Create a new project in your favorite IDE

I'm going to be using VScode for this tutorial. Feel free to use the editor of your choice. Let's go ahead and set up
our html code.

HTML:



<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Screen Sharing</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>

<body>
    <div style="width:80%;background: grey;margin: auto;">
        <video id="video" autoplay playsinline muted></video>
    </div>
    <div style="width:80%;margin: auto;padding-top:10px ;">
        <button class="btn btn-primary" id="start"> Start Screen Sharing</button>
        <button class="btn btn-secondary" id="stop"> Stop</button>
    </div>
</body>

</html>


Enter fullscreen mode Exit fullscreen mode

Start your live-server and open the index.html file in your browser. You should see a page that looks like this:

Image description

JavaScript:

Next, we need to add some JavaScript code to our index.html file. Go ahead and add your script tags to the body section
of your index.html file and add the following code:



const videoElem = document.getElementById("video");
      const startElem = document.getElementById("start");
      const stopElem = document.getElementById("stop");
      // Options for getDisplayMedia()
      var displayMediaOptions = {
          video: {
              cursor: "always",
              height: 1000,
              width: 1200
          },
          audio: false
      };
      // Set event listeners for the start and stop buttons
      startElem.addEventListener("click", function (evt) {
          startCapture();
      }, false);
      // Stop the screen capture
      stopElem.addEventListener("click", function (evt) {
          stopCapture();
      }, false);
      // Start the screen capture
      async function startCapture() {
          try {
              videoElem.srcObject = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
              dumpOptionsInfo();
          } catch (err) {
              // Handle error
              console.error("Error: " + err);
          }
      }
      // Stop the stream
      function stopCapture(evt) {
          let tracks = videoElem.srcObject.getTracks();
          tracks.forEach(track => track.stop());
          videoElem.srcObject = null;
      }
      // Dump the available media track capabilities to the console
      function dumpOptionsInfo() {
          const videoTrack = videoElem.srcObject.getVideoTracks()[0];
          console.info("Track settings:");
          console.info(JSON.stringify(videoTrack.getSettings(), null, 2));
          console.info("Track constraints:");
          console.info(JSON.stringify(videoTrack.getConstraints(), null, 2));
}


Enter fullscreen mode Exit fullscreen mode

Test the Application

Now we can go ahead and test our application. Open the index.html file in your browser and click on the start button to
initialize the screen capture.

Image description

Click on a screen and you should see the video stream of the screen you clicked on. You can also click on the stop
button to stop the screen capture.

Image description

Full Code:



<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Screen Sharing</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>

<body>
    <div style="width:80%;background: grey;margin: auto;">
        <video id="video" autoplay playsinline muted></video>
    </div>
    <div style="width:80%;margin: auto;padding-top:10px ;">
        <button class="btn btn-primary" id="start"> Start Screen Sharing</button>
        <button class="btn btn-secondary" id="stop"> Stop</button>
    </div>
    <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",
                height: 1000,
                width: 1200
            },
            audio: false
        };
        // Set event listeners for the start and stop buttons
        startElem.addEventListener("click", function (evt) {
            startCapture();
        }, false);
        stopElem.addEventListener("click", function (evt) {
            stopCapture();
        }, false);
        async function startCapture() {
            try {
                videoElem.srcObject = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
                dumpOptionsInfo();
            } 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];
            console.info("Track settings:");
            console.info(JSON.stringify(videoTrack.getSettings(), null, 2));
            console.info("Track constraints:");
            console.info(JSON.stringify(videoTrack.getConstraints(), null, 2));
        }
    </script>
</body>
</html>


Enter fullscreen mode Exit fullscreen mode

🤝 Thank you so much for taking time out of your day to read this Article! I hope it helped you out and you learned something new today! Please leave a comment if you have anything you'd like to add.

☕️ If you enjoy reading my content Buy me a coffee as it will help me continue to make awesome quality blogs!

👨🏽‍💻 For more Web Dev code snippets, tips, and tricks check out my Grepper Platform

🎨 You can also check out my Portfolio here

🐦 You can also follow me on Twitter to check out my self-taught journey as well as more bite-sized tips on web development.

Top comments (4)

Collapse
 
fnaquira profile image
Favio Náquira

Where is the WebRTC part? Is it going to be a second part?

Collapse
 
anthonys1760 profile image
Anthony Smith

Yes, WebRTC is coming soon and will be a second part for sure.

Collapse
 
norantio profile image
nick

Were you able to create a second part for this? I am very much interested in this.

Collapse
 
omwalunj profile image
Om DIlip Walunj

where should i can get the second part of this project?