Issue getting full page Screenshot of website using PageSpeedApi and Google Apps Script

320 views Asked by At

I am trying to get the screenshot from this link to Google Drive using Google Apps Script. For that, I found this source to make it work. I tried to modify the script but the result is not exactly what I am looking to achieve. Here is the script:

    function getScreenShot(){

       const apiKey = "###"; 
       const url1 = "http://www.amafruits.com"; 
       const apiEndpoint = `https://www.googleapis.com/pagespeedonline/v5/runPagespeed?key=${apiKey}&url=${encodeURIComponent(url1)}&category=performance&strategy=mobile`;
    
          const res = UrlFetchApp.fetch(apiEndpoint)
          const obj = JSON.parse(res.getContentText());
          const base64 = obj["lighthouseResult"]["audits"]["final-screenshot"][
            "details"
          ]["data"]
            .split(",")
            .pop();
          const blob = Utilities.newBlob(
            Utilities.base64Decode(base64),
            "image/jpeg",
            "sample1.jpg"
          );
          const id = DriveApp.createFile(blob).getId();
          console.log(id);
        }

However, it gives the following output:

Output Image

Ideally, I want to get the following screenshot from the website:

Image Result

How do I get the full page screenshot instead of just one small portion? Any guidance would be much appreciated. Thank you for your time.

1

There are 1 answers

5
Tanaike On BEST ANSWER

In your situation, how about the following sample script?

Sample script:

In this sample script, I retrieved the screenshot from https://pagespeed.web.dev/report?url=http%3A%2F%2Fwww.amafruits.com%2F using Charts Service.

function myFunction() {
  const url = "https://pagespeed.web.dev/report?url=http%3A%2F%2Fwww.amafruits.com%2F"; // This URL is from your question.

  const blob = Charts
    .newTableChart()
    .setDataTable(Charts.newDataTable().addColumn(Charts.ColumnType.STRING, "").addRow([`<meta http-equiv="refresh" content="0; URL='${url}'">`]).build())
    .setOption('allowHtml', true)
    .setDimensions(1000, 2000)
    .build()
    .getBlob();
  DriveApp.createFile(blob.setName("sample.png"));
}
  • When this script is run, the whole page is retrieved as a PNG file. That image includes your expected situation. Unfortunately, if you want to retrieve only your showing image, it is required to edit the exported image.

Note:

  • In this case, when the image size is smaller than the HTML page, please adjust .setDimensions(1000, 2000), and test it again.
  • In this sample, it seems that all URLs cannot be used. Please be careful about this.

Reference: