google-apps-scriptgoogle-drive-apiscreenshotgoogle-pagespeed-insights-api

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


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.


Solution

  • 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"));
    }
    

    Note:

    Reference: