Skip to content

How to take a Screenshot and Save using JavaScript AJAX and PHP

How-to-take-a-Screenshot-and-Save-using-JavaScript-AJAX-and-PHP

We will see how to capture and save webpage screenshots using JavaScript, AJAX, and PHP. These methods give solutions to take screenshots using libraries.

I am 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.

index.html

<h1>Capture Screenshot of Page Using the html2canvas JavaScript library</h1>
<button id="btn_capture">Capture</button>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>

<script>
jQuery('#btn_capture').click(function(){
    const t=document.body;
    html2canvas(t).then(
        canvas=>{
            document.body.appendChild(canvas);
            url_data=canvas.toDataURL();
            jQuery.ajax({
                url:'process.php',
                type:'post',
                data:{
                    img:url_data
                },
                dataType:"html",
                success:function(result){
                    console.log(result);
                }
            });	
    });
});
</script>

	How-to-take-a-Screenshot-and-Save-using-JavaScript-AJAX-and-PHP

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.

process.php

<?php
if(isset($_POST['img'])){
    $source=fopen($_POST['img'],"r");
    $image_name=time().'.png';
    $destination=fopen('images/'.$image_name,"w");
    stream_copy_to_stream($source,$destination);
    fclose($source);
    fclose($destination);
}
?>

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

Good luck and I hope this article can be useful. See you in the next article…

If you enjoyed this tutorial and learned something from it, please consider sharing it with our friends and followers! Also like to my facebook page to get more awesome tutorial each week!

Leave a Reply

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