This is a sample script for retrieving screen shots of sites using Google Apps Script. In order to retrieve the screen shot, here, I used PageSpeed API.
When you use this, please copy and paste the following script, and set an URL you want to retrieve a screen shot.
var siteUrl = "### URL you want to retrieve a screen shot. ###";
var url =
"https://www.googleapis.com/pagespeedonline/v4/runPagespeed?screenshot=true&fields=screenshot&url=" +
encodeURIComponent(siteUrl);
var res = UrlFetchApp.fetch(url).getContentText();
var obj = JSON.parse(res);
var blob = Utilities.newBlob(
Utilities.base64DecodeWebSafe(obj.screenshot.data),
"image/png",
"sample.png"
);
DriveApp.createFile(blob);
Note :
- Retrieved value of screen shot is a base64 data with Web Safe.
- In my environment, when I ran this script as a test, it was not required to enable this API at API console. And also I used no API key. If you want to retrieve values from a lot of URLs, it might be required to enable API and use API key.
Updated at December 9, 2021
Now, version 5 can be used. The script is as follows. In this case, please add the scope as the value of openid
. By this, the access token can be used. Although this sample script uses the access token, of course, you can also use the API key instead of the access token.
function myFunction() {
const siteUrl = "https://tanaikech.github.io/"; // Please set the site URL.
const url = `https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=${encodeURIComponent(
siteUrl
)}&fields=${encodeURIComponent("lighthouseResult")}`;
const res = UrlFetchApp.fetch(url, {
muteHttpExceptions: true,
headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() },
});
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);
}