How To Create a Screen Sharing Application With JavaScript
Tags: javascript, html, css, webdev
Published: 2022-08-08 18:04:00

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:
```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>
```
Start your live-server and open the index.html file in your browser. You should see a page that looks like this:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0j2bysg2tlo8wh4j9lgt.png)

# 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:
```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);
      // 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));
}
```

# 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p9xkr3osty4jvbao5r08.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3jchxbrj8my9sjs0h7xd.png)

## Full 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>
    <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>
```
<hr>

🤝 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 <a href="https://www.buymeacoffee.com/tonysmith2077">Buy me a coffee</a> as it will help me continue to make awesome quality blogs!

👨🏽‍💻 For more Web Dev code snippets, tips, and tricks check out my <a href="https://www.codegrepper.com/profile/anthony-smith">Grepper Platform</a>

🎨 You can also check out my Portfolio  <a href="https://anthonysdigital.net/">here</a>

🐦 You can also follow me on <a href="https://twitter.com/tonycodesdaily">Twitter</a> to check out my self-taught journey as well as more bite-sized tips on web development.