How to Capture Screenshot of Page using JavaScript

by Vincy. Last modified on July 3rd, 2023.

We will see three different ways of capturing webpage screenshots using JavaScript. These three methods give solutions to take screenshots with and without using libraries.

  1. I am using the html2canvas JavaScript library.
  2. I am using plain HTML5 with JavaScript.
  3. Using WebRTC’s getDisplayMedia method.

Video Demo

1) Using the html2canvas JavaScript library

This method uses the popular JS library html2canvas to capture a screenshot from a webpage.

This script implements the below steps to capture a screenshot from the page HTML.

  • It initializes the html2canvas library class and supplies the body HTML to it.
  • It sets the target to append the output screenshot to the HTML body.
  • Generates canvas element and appends to the HTML.
  • It gets the image source data URL from the canvas object.
  • Push the source URL to the PHP via AJAX to save the screenshot to the server.


Quick example

<!DOCTYPE html>
<title>How to Capture Screenshot of Page using JavaScript</title>
<link rel='stylesheet' href='form.css' type='text/css' />
    <div class="phppot-container">
        <h1>How to Capture Screenshot of Page using JavaScript</h1>
            <button id="capture-screenshot">Capture Screenshot</button>

    <script type="text/javascript"
    <script type="text/javascript">  
        $('#capture-screenshot').click(function() {
            const screenshotTarget = document.body;
            html2canvas(screenshotTarget).then(canvas => {
            	// to image as png use below line
                // const base64image = canvas.toDataURL("image/png");
            	// show the image in window use below line
                // window.location.href = base64image;
            	// screenshot appended to the body as canvas
                dataURL = canvas.toDataURL();  
                // to print the screenshot in console use below line
                // console.log(dataURL);
                // following line is optional and it is to save the screenshot
                // on the server side. It initiates an ajax call
        function pushScreenshotToServer(dataURL) {  
                url: "push-screenshot.php",  
                type: "POST",  
                data: {  
                    image: dataURL  
                dataType: "html", 
                success: function() {  
                	console.log('Screenshot pushed to server.');

We have already used this library in codes generating canvas elements with dynamic data. For example, we used html2canvas for creating invoice PDFs from HTML using JavaScript.

capture screenshot javascript

Push the screenshot to PHP to save

This PHP script reads the screenshot binaries posted via AJAX. It prepares the screenshot properties in JSON format.


if (isset($_POST['image'])) {
    // should have read and write permission to the disk to write the JSON file
    $screenshotJson = fopen("screenshot.json", "a") or die("Unable to open screenshot.json file.");
    $existingContent = file_get_contents('screenshot.json');
    $contentArray = json_decode($existingContent, true);
    $screenshotImage = array(
        'imageURL' => $_POST['image']
    $contentArray[] = $screenshotImage;
    $fullData = json_encode($contentArray);
    file_put_contents('screenshot.json', $fullData);

This will output a “screenshot.json” file with the image data URL and store it in the application.

2) Using plain HTML5 with JavaScript

This JavaScript code includes two functions. One is to generate an image object URL, and the other is to take screenshots by preparing the blob object from the page.

It prepares a blob object URL representing the output screenshot image captured from the page. It takes screenshots by clicking the “Capture Screenshot” button in the UI.

It controls the style properties and scroll coordinates of the node pushed to the screenshot object. This stops users from having the mouse controls on the BLOB object.

In a previous example, we have seen how to create a blob and store it in the MySQL database.

This code will show the captured screenshot on a new page. The new page will have the generated blob URL as a blob:http://localhost/0212cfc1-02ab-417c-b92f-9a7fe613808c


function takeScreenshot() {
	var screenshot = document.documentElement
		.cloneNode(true); = 'none'; = 'hidden'; = 'none'; = 'none'; = 'none'; = 'none'; = 'none';
	screenshot.dataset.scrollX = window.scrollX;
	screenshot.dataset.scrollY = window.scrollY;
	var blob = new Blob([screenshot.outerHTML], {
		type: 'text/html'
	return blob;

function generate() {
	window.URL = window.URL || window.webkitURL;

3) Using WebRTC’s getDisplayMedia method

This method uses the JavaScript MediaServices class to capture the screenshot from the page content.

This example uses the getDisplayMedia() of this class to return the media stream of the current page content.

Note: It needs to grant permission to get the whole or part of the page content on the display.

It prepares an image source to draw into the canvas with the reference of its context. After writing the media stream object into the context, this script converts the canvas into a data URL.

This data URL is used to see the page screenshot captured on a new page.

It should be closed after reading the media stream object to a screenshot element object. The JS MediaStreamTrack.stop() is used to close the track if unnecessary.

This JavaScript forEach iterates the MediaStream object array to get the track instance to stop.


<!DOCTYPE html>
<title>How to Capture Sceenshot of Page using JavaScript</title>
<link rel='stylesheet' href='form.css' type='text/css' />
    <div class="phppot-container">
        <p>This uses the WebRTC standard to take screenshot. WebRTC
            is popular and has support in all major modern browsers. It
            is used for audio, video communication.</p>
        <p>getDisplayMedia() is part of WebRTC and is used for
            screen sharing. Video is rendered and then page screenshot
            is captured from the video.</p>
            <button id="capture-screenshot"
    const captureScreenshot = async () => {
        const canvas = document.createElement("canvas");
        const context = canvas.getContext("2d");
        const screenshot = document.createElement("screenshot");
        try {
            const captureStream = await navigator.mediaDevices.getDisplayMedia();
            screenshot.srcObject = captureStream;
            context.drawImage(screenshot, 0, 0, window.width, window.height);
            const frame = canvas.toDataURL("image/png");
            captureStream.getTracks().forEach(track => track.stop());
            window.location.href = frame;
        } catch (err) {
            console.error("Error: " + err);

Video DemoDownload

Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page