Scroll to Top
💻
Free Code
Users get ready-to-use code at no cost.
📋
Easy Copy
Copy and use the code instantly.
Quick Learning
Understand concepts fast and clearly.
📝
Step-by-Step
Follow simple instructions to implement.
📅 August 30, 2024 💻 Tutorial ⭐ Beginner Friendly

Detect invalid urls with googleappsscript

Author Avatar

Ashish Dwivedi

Editorial Team • Tech Writer

About This Tutorial

Detect invalid URLs in Google Sheets using Google Apps Script by looping through a list of URLs and checking their response status with UrlFetchApp. If the server returns an error code (like 404 or 500), flag it as invalid in the sheet. Ideal for maintaining clean, updated, and working links.
  1. Step 1: Click on the Copy button to copy the code snippet.
  2. Step 2: Paste the copied code into your project’s script editor.

Apps Scripts Blog

Read Blog

📂 javascript
⚡ script1.js
⚡ script1.js
function checkURLs() {
  var sheet = SpreadsheetApp.getActive().getSheetByName("Sheet1"); // Change "Sheet1" if needed
  var range = sheet.getDataRange();
  var values = range.getValues();

  for (var row = 0; row < values.length; row++) {
    var url = values[row][0]; // ✅ URLs assumed to be in Column A

    if (typeof url === 'string' && url.startsWith("http")) {
      try {
        var response = UrlFetchApp.fetch(url, { muteHttpExceptions: true });
        var code = response.getResponseCode();
        var status = (code === 200) ? "Live" : "Not live";

        // ✅ Write status and response code in columns B and C
        sheet.getRange(row + 1, 2).setValue(status);
        sheet.getRange(row + 1, 3).setValue(code);
      } catch (error) {
        // ✅ Handle invalid URL or fetch errors gracefully
        sheet.getRange(row + 1, 2).setValue("Error");
        sheet.getRange(row + 1, 3).setValue(error.toString());
      }
    } else {
      // If the cell is empty or doesn't contain a valid URL
      sheet.getRange(row + 1, 2).setValue("Invalid URL");
      sheet.getRange(row + 1, 3).clearContent();
    }
  }
}