3

Using HTML5/Canvas/JavaScript to take in-browser screenshots

I follow above answer but no files can be saved at local hard disk. How to do it with javascript without external software installed ?

Edge on windows
C:\Users\hello\AppData\Local\Packages\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\AC#!001\MicrosoftEdge\User\Default\DOMStore\IS3DHS80

Chrome on windows:
%LocalAppData%\Google\Chrome\User Data\Default\Local Storage\


<html>
<body bgcolor="#000000">
<meta charset="UTF-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<script>
function save() {
let region = document.querySelector("body"); // whole screen
  html2canvas(region, {
    onrendered: function(canvas) {
      //let pngUrl = canvas.toDataURL(); // png in dataURL format
      //let img = document.querySelector(".screen");
      //img.src = pngUrl; 
      var dat = new Date();
      var a = document.createElement("a");
      a.href = canvas.toDataURL('image/png');
      a.download = dat.toString() + "_MRTG.png";
      a.hidden = true;
      document.body.appendChild(a);
      a.innerHTML = "random";
      a.click();
    },
  });
};

setTimeout(function(){
   var today = new Date();
   hours = today.getHours();
   minutes = today.getMinutes();
   if(hours === 18 && minutes === 0){
     //save();
     let b = document.querySelector("capt");
     b.click();
     setTimeout(console.log(""),5000);

   };
   window.location.reload(1);
}, 30000);


</script>
<button onclick="save()" id="capt">Screen Capture</button> 
<div id="capture">

<div class="container" id="containerr">
  <img width="75%" class="screen">
</div>
</body>
</html>
M-Askman
  • 400
  • 4
  • 17
user353573
  • 127
  • 12

6 Answers6

4

I know its not javascript, but on Ubuntu, You could schedule the following command to run in a cron job.

export now=$(date +"%m_%d_%Y") && xdg-open http://www.yahoo.com && sleep 10 && gnome-screenshot > $now.png

It assumes the page to load will load within ten seconds, and that your default browser is configured with a low enough zoom level that the entire page is legible.

mancini0
  • 4,285
  • 1
  • 29
  • 31
3

I can't see where you save the pic in your code and there're errors in your code. If I run the code in browser, I can see "container is not defined" in console. I think you should use F12 dev tools to check errors in console and correct them first.

You could use msSaveBlob in Microsoft Edge(EdgeHTML) and createObjectURL in Chrome to save the screen capture and use date time to name the image file:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
    <div>Screenshot tester</div>
    <button onclick="report()">Take screenshot</button>
    <div class="container" id="containerr">
        <img width="75%" class="screen">
    </div>
    <a id="dlink" href="#" style="display:none;">download link</a>

<script>
    function report() {
        var d = new Date();
        var n = d.getTime();
        let region = document.querySelector("body"); // whole screen
        html2canvas(region, {
            onrendered: function (canvas) {
                let pngUrl = canvas.toDataURL(); // png in dataURL format

                let img = document.querySelector(".screen");
                img.src = pngUrl;
                imgs = new Image();
                imgs.id = "containerr";
                imgs.src = img.src;
                //save file
                if (window.navigator.msSaveBlob) {
                    //IE11 & Edge 
                    var blobdata = canvas.msToBlob();
                    window.navigator.msSaveBlob(blobdata, n + ".png");
                }
                else {
                    //Other browsers 
                    canvas.toBlob(function (blob) {                           
                        $("#dlink").attr("href", window.URL.createObjectURL(blob));
                        $("#dlink").attr("download", n + ".png")
                        $("#dlink")[0].click();
                    });                       
                } 
            }
        });            
    }
</script>
</body>
</html>

---------------------------------------------------------------Edit------------------------------------------------------------

Use download.js:

<script src="download.js"></script>

function save() {
let region = document.querySelector("body"); // whole screen
  html2canvas(region, {
    onrendered: function(canvas) {
      ...
      a.click();
      if (window.navigator.msSaveBlob) { //If Edge
          download(a.href, a.download, 'image/png');
      }
    }
  });
};
Yu Zhou
  • 11,532
  • 1
  • 8
  • 22
  • I save at file:\\\c:\User\hello\Documents\screen.png, I had used html2canvas and succeed to screen capture and saved as png but the screen capture result show the image missing in screen capture result, I searched that it is 0.4.1 bug but after tried options , still can not capture the image in web, latest version of html2canvas even worser than 0.4.1 old version, it can saved as png image totally. – M-Askman Nov 18 '19 at 13:05
  • You could ask a new question and provide the detailed information of the issue you encountered with reproducible code and error message. – Yu Zhou Nov 19 '19 at 07:23
  • I test the updated code. It can work well in Chrome and the screen capture result is also well. But your code can't work in Edge, it's due to Microsoft Edge(EdgeHTML) doesn't support navigating to data URIs for [security reasons](https://learn.microsoft.com/en-us/previous-versions//cc848897(v=vs.85)?redirectedfrom=MSDN). You could use [download.js](http://danml.com/download.html) to download the file in Edge. However, Edge will still pop up a "Open or Save" dialogue and you have to manually click it. You could check my updated answer. – Yu Zhou Nov 21 '19 at 08:04
1

You can use a automated framework, like selenium. You can implement the solution in java.

With this code from this answer How to take screenshot with Selenium WebDriver, you can take the screenshot of the page you like:

WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com/");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy 
    somewhere
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));

After the screenshoot you can write a repeated callback thats take the screenshot and save where you like:

LocalTime time = LocalTime.now();
if(time.compareTo(LocalTime.parse("18:00") > 0){
    //take the screenshoot
    //save the file
    //wait some time
}

More info you can consult selenium documentation: https://selenium.dev/

Guilherme
  • 456
  • 4
  • 12
0

There are two problems first one is capture and then save.

window.navigator.msSaveBlob is non standard and obsolete and may not work well, I think that is reason it is not working.

I got an idea and wants to share it with you.What about developing a chrome extension which is configured to allow on your selected domain (in case if you want to be enabled on your website only).It can easily do DOM manipulations with your content and has ability to write and store files in to user's local file system.Please check here for more details about FileSystem Otherwise HTML 5 FileSystem API should be working fine

  localstorage.root.getFile("screenhot-25112019.PNG", {create: true});

To take screen shots you can check code here

However it will limit your scope to chrome only.

  • after tried , but no new window pop up, https://github.com/hoyeunglee/Testing/blob/master/ScreenCapture.html – M-Askman Nov 27 '19 at 08:24
0

You can try to put the file into folders of the year. That way you will keep everything more organized and there will never be conflicts because every month and day will be unique.

Luis Liz
  • 1,939
  • 4
  • 20
  • 31
0

You can achieve this by using below with some javascript code. https://html2canvas.hertzen.com/

This will covert the page into a canvas and then you can trigger the download. It also supports different options such as ignoreElements and timeout. You can check all available configurations in here https://html2canvas.hertzen.com/configuration

html2canvas(document.querySelector("#capture")).then(canvas => {
    $("#img-holder").append(canvas);
    download(canvas, 'myimage.png'); 
});


function download(canvas, filename) {
  /// create an "off-screen" anchor tag
  var lnk = document.createElement('a'), e;

  /// the key here is to set the download attribute of the a tag
  lnk.download = filename;

  /// convert canvas content to data-uri for link. When download
  /// attribute is set the content pointed to by link will be
  /// pushed as "download" in HTML5 capable browsers
  lnk.href = canvas.toDataURL("image/png;base64");

  /// create a "fake" click-event to trigger the download
  if (document.createEvent) {
    e = document.createEvent("MouseEvents");
    e.initMouseEvent("click", true, true, window,
                     0, 0, 0, 0, 0, false, false, false,
                     false, 0, null);

    lnk.dispatchEvent(e);
  } else if (lnk.fireEvent) {
    lnk.fireEvent("onclick");
  }
}

You can check the working code in the fiddle.

https://jsfiddle.net/athishayd/ronq0tmg/5/

MrAJ
  • 95
  • 5