Main function to start the process
*/
function main() {
try {
// Get sitemap URL from user
const sitemapUrl = Browser.inputBox(
'Sitemap URL Input',
'Please enter the sitemap URL:',
Browser.Buttons.OK_CANCEL
);
if (sitemapUrl === 'cancel' || !sitemapUrl) {
Browser.msgBox('Process cancelled by user.');
return;
}
// Validate URL
if (!isValidUrl(sitemapUrl)) {
Browser.msgBox('Invalid URL provided. Please enter a valid sitemap URL.');
return;
}
Browser.msgBox('Starting sitemap processing. This may take several minutes...');
// Fetch URLs from sitemap
const urls = fetchSitemapUrls(sitemapUrl);
if (urls.length === 0) {
Browser.msgBox('No URLs found in the sitemap.');
return;
}
Setup URL sheet with formatting
*/
function setupUrlSheet(sheet, urls) {
// Set headers
const headers = ['Sr.No', 'URL'];
sheet.getRange(1, 1, 1, headers.length).setValues([headers]);
// Format header row
const headerRange = sheet.getRange(1, 1, 1, headers.length);
headerRange.setBackground('#4a90e2'); // Dark cornflower blue
headerRange.setFontColor('#ffffff'); // White text
headerRange.setFontWeight('bold');
headerRange.setHorizontalAlignment('center');
// Add URLs with serial numbers
const data = urls.map((url, index) => [index + 1, url]);
if (data.length > 0) {
sheet.getRange(2, 1, data.length, 2).setValues(data);
}
Setup metadata sheet with formatting
*/
function setupMetadataSheet(sheet) {
// Set headers
const headers = ['Sr.No', 'URL', 'Meta Title', 'Meta Description', 'H1 Heading'];
sheet.getRange(1, 1, 1, headers.length).setValues([headers]);
// Format header row
const headerRange = sheet.getRange(1, 1, 1, headers.length);
headerRange.setBackground('#4a90e2'); // Dark cornflower blue
headerRange.setFontColor('#ffffff'); // White text
headerRange.setFontWeight('bold');
headerRange.setHorizontalAlignment('center');
console.log(`Processing batch ${batchIndex + 1}/${batches} (URLs ${startIndex + 1}-${endIndex})`);
// Process each URL in the batch
const batchData = [];
for (let i = 0; i < batchUrls.length; i++) {
const url = batchUrls[i];
const urlIndex = startIndex + i;
try {
const metadata = extractMetadata(url);
batchData.push([
urlIndex + 1, // Sr.No
url,
metadata.title || 'N/A',
metadata.description || 'N/A',
metadata.h1 || 'N/A'
]);
// Small delay between requests
if (i < batchUrls.length - 1) {
Utilities.sleep(CONFIG.DELAY_BETWEEN_REQUESTS);
}
} catch (error) {
console.error(`Error processing URL ${url}:`, error);
batchData.push([
urlIndex + 1,
url,
'ERROR',
'Failed to fetch',
'ERROR'
]);
}
}
// Write batch data to sheet
if (batchData.length > 0) {
const startRow = startIndex + 2; // +2 because row 1 is header and we start from row 2
sheet.getRange(startRow, 1, batchData.length, 5).setValues(batchData);
}
// Delay between batches (except for the last batch)
if (batchIndex < batches - 1) {
Utilities.sleep(CONFIG.DELAY_BETWEEN_BATCHES);
}
}
}
/**
Extract metadata from a URL
*/
function extractMetadata(url) {
try {
const response = UrlFetchApp.fetch(url, {
method: 'GET',
followRedirects: true,
muteHttpExceptions: true,
headers: {
'User-Agent': 'Mozilla/5.0 (compatible; Google Apps Script)'
}
});
if (response.getResponseCode() !== 200) {
throw new Error(HTTP ${response.getResponseCode()});
}
const html = response.getContentText();
// Extract meta title
let title = '';
const titleMatch = html.match(/]>(.?)</title>/is);
if (titleMatch) {
title = titleMatch[1].replace(/\s+/g, ' ').trim();
}
// Extract meta description
let description = '';
const descMatch = html.match(/]*name=["']description["'][^>]content="'["'][^>]>/i);
if (descMatch) {
description = descMatch[1].replace(/\s+/g, ' ').trim();
}
Utility function to clean up HTML entities
*/
function cleanHtmlEntities(text) {
return text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(/ /g, ' ')
.trim();
}
/**
Test function for development
*/
function testFunction() {
// Test with a sample sitemap URL
const testUrl = 'https://example.com/sitemap.xml';
console.log('Testing with URL:', testUrl);
Sure! I fixed the errors in your code, cleaned up regexes, improved some logic (especially for parsing sitemap XML and metadata extraction), and removed unused / incorrect parts (e.g., cleanHtmlEntities was not functional and unnecessary). Here is the corrected and cleaned-up version of your Google Apps Script code:
javascript
/**
* Sitemap URL Fetcher and Metadata Extractor
* Fetches URLs from sitemap and extracts metadata
* Author: Generated by AI Assistant
* Version: 1.0
*/
// Configuration
const CONFIG = {
MAX_URLS: 800,
BATCH_SIZE: 20,
DELAY_BETWEEN_BATCHES: 1000, // milliseconds
DELAY_BETWEEN_REQUESTS: 100, // milliseconds
TIMEOUT: 10000 // 10 seconds
};
/**
* Main function to start the process
*/
function main() {
try {
// Get sitemap URL from user
const sitemapUrl = Browser.inputBox(
'Sitemap URL Input',
'Please enter the sitemap URL:',
Browser.Buttons.OK_CANCEL
);
if (sitemapUrl === 'cancel' || !sitemapUrl) {
Browser.msgBox('Process cancelled by user.');
return;
}
// Validate URL
if (!isValidUrl(sitemapUrl)) {
Browser.msgBox('Invalid URL provided. Please enter a valid sitemap URL.');
return;
}
Browser.msgBox('Starting sitemap processing. This may take several minutes...');
// Fetch URLs from sitemap
const urls = fetchSitemapUrls(sitemapUrl);
if (urls.length === 0) {
Browser.msgBox('No URLs found in the sitemap.');
return;
}
// Create or clear sheets
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
const urlSheet = createOrClearSheet(spreadsheet, 'URLs');
const metadataSheet = createOrClearSheet(spreadsheet, 'Metadata');
// Setup URL sheet
setupUrlSheet(urlSheet, urls);
// Setup metadata sheet
setupMetadataSheet(metadataSheet);
// Process URLs for metadata
processUrlsForMetadata(urls, metadataSheet);
Browser.msgBox(`Process completed! Found ${urls.length} URLs and extracted metadata.`);
} catch (error) {
console.error('Error in main function:', error);
Browser.msgBox('An error occurred: ' + error.toString());
}
}
/**
* Validate URL format
*/
function isValidUrl(string) {
try {
new URL(string);
return true;
} catch (_) {
return false;
}
}
/**
* Fetch URLs from sitemap
*/
function fetchSitemapUrls(sitemapUrl, collectedUrls = []) {
try {
console.log('Fetching sitemap from:', sitemapUrl);
const response = UrlFetchApp.fetch(sitemapUrl, {
method: 'GET',
followRedirects: true,
muteHttpExceptions: true,
headers: {
'User-Agent': 'Mozilla/5.0 (compatible; Google Apps Script)'
},
timeout: CONFIG.TIMEOUT
});
if (response.getResponseCode() !== 200) {
throw new Error(`Failed to fetch sitemap. Status: ${response.getResponseCode()}`);
}
const xmlContent = response.getContentText();
// Check if sitemap index or URL set
const isSitemapIndex = /<sitemapindex[\s\S]*?>/i.test(xmlContent);
if (isSitemapIndex) {
// Parse sitemapindex and fetch each sitemap recursively (limit to 10 to avoid deep recursion)
const locMatches = [...xmlContent.matchAll(/<loc>(.*?)<\/loc>/gi)];
const maxSitemaps = 10;
for (let i = 0; i < Math.min(locMatches.length, maxSitemaps); i++) {
const loc = locMatches[i][1].trim();
if (isValidUrl(loc)) {
fetchSitemapUrls(loc, collectedUrls);
if (collectedUrls.length >= CONFIG.MAX_URLS) break;
}
}
} else {
// Parse urlset and extract URLs
const locMatches = [...xmlContent.matchAll(/<loc>(.*?)<\/loc>/gi)];
for (const match of locMatches) {
const url = match[1].trim();
if (url && isValidUrl(url)) {
collectedUrls.push(url);
if (collectedUrls.length >= CONFIG.MAX_URLS) break;
}
}
}
console.log(`Current collected URLs count: ${collectedUrls.length}`);
return collectedUrls.slice(0, CONFIG.MAX_URLS);
} catch (error) {
console.error('Error fetching sitemap:', error);
throw new Error('Failed to fetch sitemap: ' + error.toString());
}
}
/**
* Create or clear sheet
*/
function createOrClearSheet(spreadsheet, sheetName) {
let sheet = spreadsheet.getSheetByName(sheetName);
if (sheet) {
sheet.clear();
} else {
sheet = spreadsheet.insertSheet(sheetName);
}
return sheet;
}
/**
* Setup URL sheet with formatting
*/
function setupUrlSheet(sheet, urls) {
// Set headers
const headers = ['Sr.No', 'URL'];
sheet.getRange(1, 1, 1, headers.length).setValues([headers]);
// Format header row
const headerRange = sheet.getRange(1, 1, 1, headers.length);
headerRange.setBackground('#4a90e2'); // Dark cornflower blue
headerRange.setFontColor('#ffffff'); // White text
headerRange.setFontWeight('bold');
headerRange.setHorizontalAlignment('center');
// Add URLs with serial numbers
const data = urls.map((url, index) => [index + 1, url]);
if (data.length > 0) {
sheet.getRange(2, 1, data.length, 2).setValues(data);
}
// Auto-resize columns
sheet.autoResizeColumns(1, headers.length);
// Freeze header row
sheet.setFrozenRows(1);
}
/**
* Setup metadata sheet with formatting
*/
function setupMetadataSheet(sheet) {
// Set headers
const headers = ['Sr.No', 'URL', 'Meta Title', 'Meta Description', 'H1 Heading'];
sheet.getRange(1, 1, 1, headers.length).setValues([headers]);
// Format header row
const headerRange = sheet.getRange(1, 1, 1, headers.length);
headerRange.setBackground('#4a90e2'); // Dark cornflower blue
headerRange.setFontColor('#ffffff'); // White text
headerRange.setFontWeight('bold');
headerRange.setHorizontalAlignment('center');
// Auto-resize columns
sheet.autoResizeColumns(1, headers.length);
// Freeze header row
sheet.setFrozenRows(1);
}
/**
* Process URLs for metadata extraction
*/
function processUrlsForMetadata(urls, sheet) {
const totalUrls = urls.length;
const batches = Math.ceil(totalUrls / CONFIG.BATCH_SIZE);
console.log(`Processing ${totalUrls} URLs in ${batches} batches`);
for (let batchIndex = 0; batchIndex < batches; batchIndex++) {
const startIndex = batchIndex * CONFIG.BATCH_SIZE;
const endIndex = Math.min(startIndex + CONFIG.BATCH_SIZE, totalUrls);
const batchUrls = urls.slice(startIndex, endIndex);
console.log(`Processing batch ${batchIndex + 1}/${batches} (URLs ${startIndex + 1}-${endIndex})`);
// Process each URL in the batch
const batchData = [];
for (let i = 0; i < batchUrls.length; i++) {
const url = batchUrls[i];
const urlIndex = startIndex + i;
try {
const metadata = extractMetadata(url);
batchData.push([
urlIndex + 1, // Sr.No
url,
metadata.title || 'N/A',
metadata.description || 'N/A',
metadata.h1 || 'N/A'
]);
// Small delay between requests except after last url in batch
if (i < batchUrls.length - 1) {
Utilities.sleep(CONFIG.DELAY_BETWEEN_REQUESTS);
}
} catch (error) {
console.error(`Error processing URL ${url}:`, error);
batchData.push([
urlIndex + 1,
url,
'ERROR',
'Failed to fetch',
'ERROR'
]);
}
}
// Write batch data to sheet
if (batchData.length > 0) {
const startRow = startIndex + 2; // +2 because row 1 is header and data starts from row 2
sheet.getRange(startRow, 1, batchData.length, 5).setValues(batchData);
}
// Delay between batches, except after last batch
if (batchIndex < batches - 1) {
Utilities.sleep(CONFIG.DELAY_BETWEEN_BATCHES);
}
}
}
/**
* Extract metadata from a URL
*/
function extractMetadata(url) {
try {
const response = UrlFetchApp.fetch(url, {
method: 'GET',
followRedirects: true,
muteHttpExceptions: true,
headers: {
'User-Agent': 'Mozilla/5.0 (compatible; Google Apps Script)'
},
timeout: CONFIG.TIMEOUT
});
if (response.getResponseCode() !== 200) {
throw new Error(`HTTP ${response.getResponseCode()}`);
}
const html = response.getContentText();
// Extract meta title
let title = '';
const titleMatch = html.match(/<title[^>]*>([^<]+)<\/title>/i);
if (titleMatch) {
title = titleMatch[1].trim().replace(/\s+/g, ' ');
}
// Extract meta description
let description = '';
// This pattern looks for meta description tag with content attribute, case-insensitive
const descMatch = html.match(/<meta\s+name=["']description["']\s+content=["']([^"']*)["']/i);
if (descMatch) {
description = descMatch[1].trim().replace(/\s+/g, ' ');
}
// Extract H1 heading (first h1)
let h1 = '';
const h1Match = html.match(/<h1[^>]*>([\s\S]*?)<\/h1>/i);
if (h1Match) {
// Remove any inner HTML tags and trim
h1 = h1Match[1].replace(/<[^>]*>/g, '').trim().replace(/\s+/g, ' ');
}
return {
title: title,
description: description,
h1: h1
};
} catch (error) {
console.error(`Error extracting metadata from ${url}:`, error);
throw error;
}
}
/**
* Test function for development
*/
function testFunction() {
// Test with a sample sitemap URL
const testUrl = 'https://example.com/sitemap.xml';
console.log('Testing with URL:', testUrl);
try {
const urls = fetchSitemapUrls(testUrl);
console.log('Found URLs:', urls.length);
if (urls.length > 0) {
const metadata = extractMetadata(urls[0]);
console.log('Sample metadata:', metadata);
}
} catch (error) {
console.error('Test error:', error);
}
}
Main fixes and improvements I made:
Sitemap parsing:
Fixed sitemap index detection to use a proper RegExp instead of empty string check.
Used matchAll with <loc>(.*?)</loc> for accurate URL extraction.
Corrected recursive call and collection of URLs with a collectedUrls array passed as argument to avoid duplicates and to limit the total URLs.
Metadata extraction:
Fixed regex patterns to valid expressions:
Title: /\<title[^>]*\>([^<]+)\<\/title\>/i
Meta description: /\<meta\s+name=["']description["']\s+content=["']([^"']*)["']/i
H1: /\<h1[^>]*\>([\s\S]*?)\<\/h1\>/i
Also stripped inner HTML tags from H1 content.
Removed incorrect or broken code:
The previous cleanHtmlEntities function was both incorrect (not unescaping but replacing with literal characters equal to the entities) and not used anywhere, so I removed it.
Timeout added to UrlFetchApp calls to avoid hanging.
Better error handling and logging for debugging.
Batch processing preserved with delays between requests and batches for throttling.
You can now use main() to run the entire workflow, and use testFunction() to test with a sample sitemap URL (replace the URL with a real sitemap to try).
Let me know if you want me to add other features or help with deployment!