ITHCWY: Robert Ellison's Blog

Get an email if your site stops being mobile friendly

Get an email if your site stops being mobile friendly

Google just released an API for the mobile friendly test and so I've whipped up a script to send an alert if a web page violates their guidelines. This will run the test as often as you like and send you an email if it detects a problem. Alternatively if you're not mobile friendly it will keep emailing you until you fix any problems which might be a good motivational tool.

First start a new apps script project in drive and paste in the code below:

var urlToMonitor = '';
var alertEmail = '';
var runTestKey = '';

var runTestUrl = 'https://searchconsole.googleapis.com/v1/urlTestingTools/mobileFriendlyTest:run?key=';

function mobileFriendlyMonitor() {
  try {
    
    var postBody = {
      'url' : urlToMonitor
    };
      
    var options = {
      'method' : 'post',
      'contentType': 'application/json',
      'payload' : JSON.stringify(postBody)
    };
    
    var response = UrlFetchApp.fetch(runTestUrl + runTestKey, options);
    var json = response.getContentText();
    var mobileFriendlyResult = JSON.parse(json);
    
    if (mobileFriendlyResult.mobileFriendliness != 'MOBILE_FRIENDLY') {
      sendEmail('Mobile friendly test failed for ' + urlToMonitor + ', check https://search.google.com/search-console/mobile-friendly for details');
    }
      
  } catch (e) {
    sendEmail('mobileFriendlyMonitor failed for: ' + urlToMonitor + ' with error: ' + e.message);
  }
}

function sendEmail(msg) {
  MailApp.sendEmail(alertEmail, 'Mobile Friendly Monitor Alert on ' + Utilities.formatDate(new Date(), "GMT""yyyy-MM-dd'T'HH:mm:ss'Z'"), msg);
}

There are three variables you need to set, urlToMonitor is the full URL of the page to test, alertEmail is your email address (or whoever needs to be pestered) and runTestKey is the API key for the service. To get this go to the Google API Console, click Enable API, search for 'Google Search Console URL Testing Tools API' and click enable. Then click the Credentials option and generate a browser key.

Once you've configured the script choose 'Current project's triggers' from the Resources menu in apps script and set up a schedule for the mobileFriendlyMonitor() function.

Add Comment

All comments are moderated to weed out spam. Email address is optional and is only used to display your Gravatar.