It is important for each site owner to be sure that at the moment his online resource is available and working properly. Well, if, suddenly, a problem occurs, then the site owner should find out about it before everyone else.
There are a huge number of paid and shareware services that are ready to provide round-the-clock monitoring of web resources. And, in case of their unavailability, immediately inform the interested party about it.
However, there is a very simple way to run this check yourself, in a convenient mode and completely free of charge.
The idea is simple: using Google Apps Script, we send a request to the specified url and parse the response code. If the response code is 200, it does nothing. Well, if not, we send an error message to our email.
The script that implements this task is below:
function locator() {
let sites = ['https://it4each.com/',
];
let myEmail = YourEmail;
let subject = "Site not working!!!";
let errors = [];
// request sending and processing loop
for (const site of sites) {
try {
let response = UrlFetchApp.fetch(site);
if (response.getResponseCode() != 200 ) errors.push(site);
} catch (e) {
let error_messege = e.name + ': for website ' + site + '\n';
console.error(error_messege);
errors.push(site)
};
};
// send email
if (errors.length > 0) {
let message = "";
for (let error of errors) {
message += 'Website ' + error + " doesn't working!\n";
};
message += '\n' + 'Remaining Daily Quota: ' + MailApp.getRemainingDailyQuota();
MailApp.sendEmail(myEmail, subject, message)
};
}
The locator() function monitors the operation of sites. Previously, the following initial data must be passed to this function:
Next comes the cycle of sending and processing requests. This is done using the standard fetch(url) method of the UrlFetchApp class.
If the resource is available in principle, but its response code is not 200, then the name of the problematic resource is added to the errors error list on the same line.
But if the resource is not available at all, then UrlFetchApp.fetch(site) will give an error that can cause the program to stop. To prevent this from happening, we will process a variant of such an error through try - catch(e). And adding the name of this site will happen this time in the catch block.
The result will be processed below, in the send email block.
If the list of errors is not empty, then message will be generated in the loop, where all non-working sites will be listed. Additionally, information will be added on how many similar email messages can still be created today in order not to exceed the quota: MailApp.getRemainingDailyQuota().
The script is ready. But in order to carry out full-fledged monitoring, you need to run this script regularly and around the clock. Therefore, we need to install a trigger.
You can learn how to create and configure a trigger, as well as get more information about how this script works, from this video (RU voice):