Detect invalid urls with googleappsscript

August 30, 2024 | 1 minute read


Editorial Team

blog-image

AppSScript Code

function checkURLs() {
  var sheet = SpreadsheetApp.getActive().getSheetByName("Sheet1"); // Replace "Sheet1" with the name of your sheet
  var range = sheet.getDataRange();
  var values = range.getValues();
  
  for (var row = 0; row < values.length; row++) {
    var url = values[row][0]; // Assuming URLs are in the first column of your sheet
    
    if (url.indexOf("http") === 0) { // Check if URL starts with "http" or "https"
      var options = {
        'muteHttpExceptions': true
      };
      var response = UrlFetchApp.fetch(url, options);
      var code = response.getResponseCode();
      var status = (code === 200) ? "Live" : "Not live"; // Check if URL returns a 200 response code
      
      sheet.getRange(row+1, 2).setValue(status); // Write the status in the second column of the current row
      sheet.getRange(row+1, 3).setValue(code); // Write the response code in the third column of the current row
    }
  }
}