How to Take Simple Screenshot in Vanilla JavaScript

1

How to Take Screenshots in Vanilla JavaScript

Did you know you can take or capture screenshots of any window using vanilla JavaScript? Yes, there’s no need for an external library or plugin to take a simple screenshot of the web page or window.

If you don’t know, I previously shared a blog on How to Take Screenshots using JavaScript HTML2Canvas. HTML2Canvas is a JavaScript library for taking screenshots of entire or parts of a webpage.

However, in this blog, you will learn to do the same thing (capturing screenshots) with plain JavaScript. The codes and logic behind taking a screenshot are so easy that you can easily understand them if you have some basic JavaScript knowledge.

To take a screenshot, I’ve created a dummy web page with some headings, paragraphs, and a button. When the user clicks on the button, a prompt window will be shown asking for permission to capture a screenshot. If the user accepts the permission, the webpage will be screenshotted and shown as an image lightbox.

If you’re excited to know how these actually look, you can watch the given YouTube video on How to Take Screenshots in JavaScript.

Video Tutorial of Taking Screenshot in JavaScript

I hope you liked the demo of Taking Screenshots and understood how I created it using vanilla JavaScript. I’ve shown the screenshot as a simple image lightbox. However, it can be easily used in a feedback form or other projects.

If you don’t know, in the latest updates, YouTube does the same thing when taking screenshots in their feedback form. Earlier, they used a traditional method.

If you’ve finished watching the video and fully comprehended the codes and logic, you should be aware that by modifying some codes, you can also create a Simple Video Recorder that records the video of the user’s permitted tab.

But if you haven’t watched the video tutorial, you can continue reading the blog and follow the given steps to take screenshots. Otherwise, go to the bottom of this blog post to download the source code files.

Steps for Taking Screenshots in JavaScript

To take a screenshot using HTML, CSS, and JavaScript, follow the given steps line by line:

  1. Create a folder. You can name this folder whatever you want and put the files listed below inside it.
  2. Create an index.html file. The file name must be index and its extension .html
  3. Create a style.css file. The file name must be style and its extension .css
  4. Create a script.js file. The file name must be script and its extension .js

First, paste the following codes into your index.html file:

<!DOCTYPE html>
<!-- Coding By CodingNepal - youtube.com/codingnepal -->
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Capture Screenshots with JavaScript | CodingNepal</title>
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Font Awesome CDN Link for Icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css">
    <script src="script.js" defer></script>
  </head>
  <body>
    <h1>Capture Screenshots with JavaScript</h1>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Consequatur deserunt exercitationem quidem, voluptate amet eius. Consequuntur obcaecati ab provident, a eveniet facilis optio dolore, ut nesciunt eaque quo tenetur similique atque voluptatibus nihil nobis facere! Recusandae totam voluptates alias eveniet perspiciatis molestias voluptatibus mollitia quaerat, doloremque dolor exercitationem, nulla delectus vero vel nihil commodi error temporibus ullam dolorem repellendus adipisci?</p>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Autem blanditiis aut laboriosam perspiciatis assumenda, obcaecati esse iste! Consequuntur quam cupiditate rerum quidem neque aperiam, totam iure fugit ipsam inventore debitis quod laudantium perspiciatis ea quibusdam corporis autem ullam voluptatem. Iure nam repellendus magni assumenda, ipsa soluta facere, accusamus, possimus ab quia atque provident hic repellat. Ipsa in possimus aperiam ut, eum doloribus accusamus, excepturi, vel earum cumque atque nulla a?</p>
    <h2>Dummy heading two</h2>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Inventore consectetur maxime eum tenetur laborum delectus necessitatibus expedita dolores perferendis saepe praesentium nostrum voluptatibus porro exercitationem ipsa maiores, veniam deleniti qui dolorum, non commodi nihil magni, tempora dicta! Facilis ducimus nam consectetur exercitationem molestias labore aspernatur repellendus itaque aliquid, esse totam ipsum. Consequuntur culpa magnam obcaecati odit reprehenderit, voluptatem iste tempore.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Inventore consectetur maxime eum tenetur laborum delectus necessitatibus expedita dolores perferendis saepe praesentium nostrum voluptatibus porro exercitationem ipsa maiores, veniam deleniti qui dolorum, non commodi nihil magni, tempora dicta! Facilis ducimus nam consectetur exercitationem molestias labore aspernatur repellendus itaque aliquid, esse totam ipsum. Consequuntur culpa magnam obcaecati odit reprehenderit, voluptatem iste tempore.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Inventore consectetur maxime eum tenetur laborum delectus necessitatibus expedita dolores perferendis saepe praesentium nostrum voluptatibus porro exercitationem ipsa maiores, veniam deleniti qui dolorum, non commodi nihil magni, tempora dicta! Facilis ducimus nam consectetur exercitationem molestias labore aspernatur repellendus itaque aliquid, esse totam ipsum. Consequuntur culpa magnam obcaecati odit reprehenderit, voluptatem iste tempore.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Inventore consectetur maxime eum tenetur laborum delectus necessitatibus expedita dolores perferendis saepe praesentium nostrum voluptatibus porro exercitationem ipsa maiores, veniam deleniti qui dolorum, non commodi nihil magni, tempora dicta! Facilis ducimus nam consectetur exercitationem molestias labore aspernatur repellendus itaque aliquid, esse totam ipsum. Consequuntur culpa magnam obcaecati odit reprehenderit, voluptatem iste tempore.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Inventore consectetur maxime eum tenetur laborum delectus necessitatibus expedita dolores perferendis saepe praesentium nostrum voluptatibus porro exercitationem ipsa maiores, veniam deleniti qui dolorum, non commodi nihil magni, tempora dicta! Facilis ducimus nam consectetur exercitationem molestias labore aspernatur repellendus itaque aliquid, esse totam ipsum. Consequuntur culpa magnam obcaecati odit reprehenderit, voluptatem iste tempore.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Inventore consectetur maxime eum tenetur laborum delectus necessitatibus expedita dolores perferendis saepe praesentium nostrum voluptatibus porro exercitationem ipsa maiores, veniam deleniti qui dolorum, non commodi nihil magni, tempora dicta! Facilis ducimus nam consectetur exercitationem molestias labore aspernatur repellendus itaque aliquid, esse totam ipsum. Consequuntur culpa magnam obcaecati odit reprehenderit, voluptatem iste tempore.</p>
    
    <button id="src-btn">Capture Screenshot</button>
    <div class="src-preview">
      <div class="screenshot">
        <i id="close-btn" class="fa-solid fa-xmark"></i>
        <img src="" alt="screenshot">
      </div>
    </div>

  </body>
</html>

Second, paste the following codes into your style.css file:

/* Import Google font - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:[email protected];500;600&display=swap');
* {
  font-family: 'Poppins', sans-serif;
}
body {
  padding: 0 30px;
}
#src-btn, .screenshot {
  position: fixed;
  left: 50%;
  transform: translate(-50%, -50%);
}
#src-btn {
  bottom: 15px;
  border: none;
  outline: none;
  color: #fff;
  cursor: pointer;
  font-size: 1rem;
  padding: 15px 25px;
  border-radius: 30px;
  background: #4a98f7;
}
.src-preview {
  position: fixed;
  left: 0;
  top: 0;
  height: 100%;
  width: 100%;
  opacity: 0;
  pointer-events: none;
  background: rgba(0,0,0,0.65);
  transition: all 0.15s ease;
}
.src-preview.show {
  opacity: 1;
  pointer-events: auto;
}
.src-preview .screenshot {
  width: 70%;
  top: 50%;
  opacity: 0;
  pointer-events: none;
  aspect-ratio: 16 / 9;
  transition: transform 0.15s ease;
  transform: translate(-50%, -50%) scale(0.9);
}
.src-preview.show .screenshot{
  opacity: 1;
  pointer-events: auto;
  transform: translate(-50%, -50%) scale(1);
}
.screenshot #close-btn {
  position: absolute;
  right: -25px;
  color: #fff;
  cursor: pointer;
  font-size: 1.1rem;
}
.screenshot img {
  width: 100%;
}

Last, paste the following codes into your script.js file: If you’re having a problem understanding the JavaScript codes, I highly recommend you watch the above YouTube video to better understand which line does what.

const screenshotBtn = document.querySelector("#src-btn"),
screenshotPreview = document.querySelector(".src-preview"),
closeBtn = screenshotPreview.querySelector("#close-btn");

const captureScreen = async () => {
    try {
        // asking permission to use a media input to record current tab
        const stream = await navigator.mediaDevices.getDisplayMedia({ preferCurrentTab: true });
        const video = document.createElement("video");
        
        video.addEventListener("loadedmetadata", () => {
            const canvas = document.createElement("canvas");
            const ctx = canvas.getContext("2d");

            // passing video width & height as canvas width & height
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            
            video.play(); // playing the video so the drawn image won't be black or blank
            // drawing an image of the captured video stream
            ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
            stream.getVideoTracks()[0].stop(); // terminating first video track of the stream
            
            // passing canvas data url as screenshot preview src
            screenshotPreview.querySelector("img").src = canvas.toDataURL();
            screenshotPreview.classList.add("show");
        });
        video.srcObject = stream; // passing capture stream data as video source object
    } catch (error) { // if image couldn't capture by any reason, then alert the msg
        alert("Failed to capture screenshot!");
    }
}

closeBtn.addEventListener("click", () => screenshotPreview.classList.toggle("show"));
screenshotBtn.addEventListener("click", captureScreen);

That’s all; now you’re ready to Take Screenshots in HTML CSS, and JavaScript. If your code doesn’t work or you’ve faced any problems, you can download the source code files for this project from the given download button. It’s free, and a zip file will be downloaded that contains the project folder with source code files.

 

Previous article10 Web Development Trends to Expect in 2023
Next articleFrontend vs Backend Development – What’s the difference?

1 COMMENT

  1. This is an informative post. Got a lot of info and details from here. Thank you for sharing this and looking forward to reading more of your post.

LEAVE A REPLY

Please enter your comment!
Please enter your name here