![]() |
[Tut] How to Capture Screenshot of Page using JavaScript - Printable Version +- Sick Gaming (https://www.sickgaming.net) +-- Forum: Programming (https://www.sickgaming.net/forum-76.html) +--- Forum: PHP Development (https://www.sickgaming.net/forum-82.html) +--- Thread: [Tut] How to Capture Screenshot of Page using JavaScript (/thread-99977.html) |
[Tut] How to Capture Screenshot of Page using JavaScript - xSicKxBot - 09-23-2022 How to Capture Screenshot of Page using JavaScript <div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2022/09/how-to-capture-screenshot-of-page-using-javascript.jpg" width="550" height="413" title="" alt="" /></div><div><div class="modified-on" readability="7.1666666666667"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on September 19th, 2022.</div> <p>We are going to see three different ways of capturing screenshots of a webpage using JavaScript. These three methods give solutions to take screenshots with and without using libraries.</p> <ol> <li>Using html2canvas JavaScript library.</li> <li>Using plain HTML5 with JavaScript.</li> <li>Using WebRTC’s getDisplayMedia method.</li> </ol> <h2>1) Using the html2canvas JavaScript library</h2> <p>This method uses the popular JS library <strong>html2canvas</strong> to capture a screenshot from a webpage.</p> <p>This script implements the below steps to capture a screenshot from the page HTML.</p> <ul> <li>It initializes the <a href="https://github.com/niklasvh/html2canvas" target="_blank" rel="noopener"><em>html2canvas</em> library</a> class and supplies the body HTML to it.</li> <li>It sets the target to append the output screenshot to the HTML body.</li> <li>Generates canvas element and appends to the HTML.</li> <li>It gets the image source data URL from the canvas object.</li> <li>Push the source URL to the PHP via AJAX to save the screenshot to the server.</li> </ul> <p class="code-heading">capture-screenshot/index.html</p> <div class="post-section-highlight" readability="39"> <h3>Quick example</h3> <pre class="prettyprint"><code class="language-php-template"><!DOCTYPE html> <html> <head> <title>How to Capture Screenshot of Page using JavaScript</title> <link rel='stylesheet' href='form.css' type='text/css' /> </head> <body> <div class="phppot-container"> <h1>How to Capture Screenshot of Page using JavaScript</h1> <p> <button id="capture-screenshot">Capture Screenshot</button> </p> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script> <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 document.body.appendChild(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 pushScreenshotToServer(dataURL); }); }); function pushScreenshotToServer(dataURL) { $.ajax({ url: "push-screenshot.php", type: "POST", data: { image: dataURL }, dataType: "html", success: function() { console.log('Screenshot pushed to server.'); } }); } </script> </body> </html> </code></pre> </div> <p>We have already used this library in codes generating canvas elements with dynamic data. For example, we used html2canvas for <a href="https://phppot.com/javascript/pdf-in-javascript-html-invoice-example/">creating invoice PDFs from HTML using JavaScript</a>.</p> <p><img loading="lazy" class="alignnone size-large wp-image-19401" src="https://phppot.com/wp-content/uploads/2022/09/capture-screenshot-javascript-550x413.jpg" alt="capture screenshot javascript" width="550" height="413" srcset="https://phppot.com/wp-content/uploads/2022/09/capture-screenshot-javascript-550x413.jpg 550w, https://phppot.com/wp-content/uploads/2022/09/capture-screenshot-javascript-300x225.jpg 300w, https://phppot.com/wp-content/uploads/2022/09/capture-screenshot-javascript-768x577.jpg 768w, https://phppot.com/wp-content/uploads/2022/09/capture-screenshot-javascript.jpg 1000w" sizes="(max-width: 550px) 100vw, 550px"></p> <h3>Push the screenshot to PHP to save</h3> <p>This PHP script reads the screenshot binaries posted via AJAX. It prepares the screenshot properties in a JSON format.</p> <p class="code-heading">capture-screenshot/push-screenshot.php</p> <pre class="prettyprint"><code class="language-php"><?php 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); fclose($screenshotJson); } ?> </code></pre> <p>This will output a <em>“screenshot.json”</em> file with the image data URL and store it in the application.<br /><a class="demo" href="https://phppot.com/demo/capture-screenshot-javascript/">Video Demo</a></p> <h2>2) Using plain HTML5 with JavaScript</h2> <p>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.</p> <p>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.</p> <p>It controls the style properties and scroll coordinates of the node pushed to the screenshot object. This is to stop users have the mouse controls on the <strong>BLOB</strong> object.</p> <p>In a previous example, we have seen <a href="https://phppot.com/php/mysql-blob-using-php/">how to create a blob and store it in the MySQL database</a>.</p> <p>This code will show the captured screenshot on a new page. The new page will have the generated blob URL as blob:http://localhost/0212cfc1-02ab-417c-b92f-9a7fe613808c</p> <p class="code-heading">html5-javascript/index.html</p> <pre class="prettyprint"><code class="language-javascript">function takeScreenshot() { var screenshot = document.documentElement .cloneNode(true); screenshot.style.pointerEvents = 'none'; screenshot.style.overflow = 'hidden'; screenshot.style.webkitUserSelect = 'none'; screenshot.style.mozUserSelect = 'none'; screenshot.style.msUserSelect = 'none'; screenshot.style.oUserSelect = 'none'; screenshot.style.userSelect = '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; window.open(window.URL .createObjectURL(takeScreenshot())); } </code></pre> <h2>3) Using WebRTC’s getDisplayMedia method</h2> <p>This method uses the JavaScript <a href="https://developer.mozilla.org/en-US/docs/Web/API/Screen_Capture_API/Using_Screen_Capture" target="_blank" rel="noopener">MediaServices</a> class to capture the screenshot from the page content.</p> <p>This example uses the <strong>getDisplayMedia()</strong> of this class to return the media stream of the current page content.</p> <p><strong>Note: </strong>It needs to grant permission to get the whole or part of the page content on the display.</p> <p>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.</p> <p>This data URL is used to see the page screenshot captured on a new page.</p> <p>After reading the media stream object to a screenshot element object, it should be closed. The JS MediaStreamTrack.stop() is used to close the track if it is not needed.</p> <p>This <a href="https://phppot.com/javascript/for-each-javascript/">JavaScript forEach iterates</a> the MediaStream object array to get the track instance to stop.</p> <p class="code-heading">webrtc-get-display-media/index.html</p> <pre class="prettyprint"><code class="lannguage-php-tempplate"><!DOCTYPE html> <html> <head> <title>How to Capture Sceenshot of Page using JavaScript</title> <link rel='stylesheet' href='form.css' type='text/css' /> </head> <body> <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> <p> <p> <button id="capture-screenshot" onclick="captureScreenshot();">Capture Screenshot</button> </p> </div> <script> 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); } }; </script> </body> </html> </code></pre> <p><a class="demo" href="https://phppot.com/demo/capture-screenshot-javascript/">Video Demo</a><a class="download" href="https://phppot.com/downloads/javascript/capture-screenshot-javascript.zip">Download</a></p> <p> <!-- #comments --> </p> <div class="related-articles"> <h2>Popular Articles</h2> </p></div> <p> <a href="https://phppot.com/javascript/capture-screenshot-javascript/#top" class="top">↑ Back to Top</a> </p> </div> https://www.sickgaming.net/blog/2022/09/19/how-to-capture-screenshot-of-page-using-javascript/ |