最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to screen capture web and saved to hard disk with incremental number in filename or without overwrite file at 1

programmeradmin1浏览0评论

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=".3.1/jquery.min.js"></script>
<script src=".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>

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./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare./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>
Share Improve this question edited Nov 20, 2019 at 14:19 Lee - Ho Yeung - Martin 4004 silver badges17 bronze badges asked Nov 17, 2019 at 3:33 Lee - Ho YeungLee - Ho Yeung 12712 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 4 +25

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

export now=$(date +"%m_%d_%Y") && xdg-open http://www.yahoo. && 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.

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./ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
    <script src="https://ajax.googleapis./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');
      }
    }
  });
};

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./");
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.pareTo(LocalTime.parse("18:00") > 0){
    //take the screenshoot
    //save the file
    //wait some time
}

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

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.

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.

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

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./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/athishayd/ronq0tmg/5/

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论