Pure front-end to record screen and save video locally, so simple

Big factory technology advanced front-end Node advanced

Click above for Programmer Growth Guide and follow the official account

Reply 1, join the advanced Node communication group

08ccc6aa70fbed4ae596b0334fccaa5e.png

Author: Moment Link: https://juejin.cn/post/7280057907055869992

As a senior picture cutter, we will inevitably need to share some functions of the pages we write with others through videos. There is another scenario, that is, when we are interviewing, we need to share our screen with the interviewer. So how is this achieved?

Then let’s learn how to implement a browser screen recording function through this article.

navigator.mediaDevices

mediaDevices is a read-only property of Navigator that returns a MediaDevices object that provides connected access to media input devices such as cameras and microphones, including screen sharing.

const media = navigator.mediaDevices;

Some methods can be found through the prototype chain, as shown in the figure below:

c6d4af5101d39bd74fc2e2986ce90ba0.png

The getDisplayMedia method is used to obtain the user’s screen sharing or screen capture stream, which is usually used for applications such as screen recording or video conferencing.

navigator.mediaDevices.getDisplayMedia({
  video: true,
});

In this code, a media license containing a video stream is requested and stored in a variable named stream for later use. This stream can be used to display screen sharing on a web page or perform other media processing operations.

And because this method is asynchronous, we need to write the following code:

<body>
  <button>Share screen</button>
  <script>
    const button = document.querySelector("button");
    button.addEventListener("click", async () => {
      const stream = await navigator.mediaDevices.getDisplayMedia({
        video: true,
      });
    });
  </script>
</body>

By clicking the button button, the effect will be as shown below:

a8b75edef039e1c04b0a6ffd3e460d26.png

At this time we have obtained the stream stream.

MediaRecorder

MediaRecorder is a Web API for media recording in the browser, mainly used for recording audio and video. It allows you to capture audio and video data from different sources such as microphone, camera, screen sharing or other media elements and save it as a file or live stream it. By calling the MediaRecorder.isTypeSupported() method, it will be determined whether its MIME format can be recorded by the client. The types it supports mainly include the following methods:

const types = [
  "video/webm",
  "audio/webm",
  "video/webm;codecs=vp8",
  "video/webm;codecs=daala",
  "video/webm;codecs=h264",
  "audio/webm;codecs=opus",
  "video/mpeg",
];

In this way, you can check whether the current browser supports this type, as shown in the following code:

const mime = MediaRecorder.isTypeSupported("video/webm;codecs=h264")
  ? "video/webm;codecs=h264"
  : "video/webm";

The result is shown below:

const mediaRecorder = new MediaRecorder(stream, { mimeType: mime });

In this code, execute the new keyword to instantiate the MediaRecorder object. The structure of this object is shown below:

We can perform different operations by listening to its events, as shown in the following code:

const chunks = [];
mediaRecorder.addEventListener("dataavailable", function (e) {
  chunks.push(e.data);
});



mediaRecorder.addEventListener("stop", () => {
  const blob = new Blob(chunks, { type: chunks[0].type });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = "video.webm";
  a.click();
});

Next let’s take a look at the detailed steps of the code:

  • Listener for dataavailable events. The MediaRecorder fires this event when it has a chunk of audio/video data available. Here, whenever data is available, chunks of data (e.data) are added to the chunks array. This is to combine these chunks of data into a complete media file after recording is complete.

  • Listener for stop event. MediaRecorder fires this event when recording stops.

  • const blob = new Blob(chunks, { type: chunks[0].type });:Use the Blob constructor to combine the data chunks in the chunks array into a binary object (Blob object). chunks[0].type is used to specify the media type of the Blob, usually WebM.

  • const url = URL.createObjectURL(blob);: Use the URL.createObjectURL method to convert the Blob object into a temporary URL. This URL can be used to create a download link. Pass this url to the newly created a element for the download function.

  • a.click() triggers a download operation by simulating clicking on a hyperlink. Users will see a download dialog allowing them to save the recorded media file

In this way, a screen recording function is implemented, and an audio and video downloading function is implemented through this method.

Complete code

The complete code for this function looks like this:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button>Share screen</button>
    <script>
      const button = document.querySelector("button");
      button.addEventListener("click", async () => {
        const stream = await navigator.mediaDevices.getDisplayMedia({
          video: true,
        });

        const mime = MediaRecorder.isTypeSupported("video/webm;codecs=h264")
          ? "video/webm;codecs=h264"
          : "video/webm";

        const mediaRecorder = new MediaRecorder(stream, { mimeType: mime });

        const chunks = [];
        mediaRecorder.addEventListener("dataavailable", function (e) {
          chunks.push(e.data);
        });

        mediaRecorder.addEventListener("stop", () => {
          const blob = new Blob(chunks, { type: chunks[0].type });
          const url = URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.href = url;
          a.download = "video.webm";
          a.click();
        });
        mediaRecorder.start();
      });
    </script>
  </body>
</html>

The complete effect is shown below:

f7791f3a6e7eda6c0650059881ce48fe.png

You can also directly modify the js code on any other page, then copy and paste it directly into the console, and click on the page, as shown below:

diff

-const button = document.querySelector("button");
-button.addEventListener("click", async () => {

 + const body = document.body;
 + body.addEventListener("click", async () => {<!-- -->

Then copy and paste the code into the browser console and click on a blank space on the page:

497b48f73cc0a7613466a18f30a98cbb.png
76fbee176d55cc5461d775fe46e3af53.png

In this way, a screen recording or screen sharing function is realized.

Node community


I have formed a Node.js community with a very good atmosphere. There are many Node.js friends in it. If you are interested in learning Node.js (you can also have plans in the future), we can do Node.js-related work together. Exchange, learn and build together. Add Koala friends below and reply “Node”.

d448db797448d3d30ada21f3126581bf.png

"Share, Like, Watch" to support