getPageTitle(url) fetches a page and returns the text of its <title> tag, or '' if it cannot get one. It does not throw on ordinary failures (a 404, a blocked request, or HTML with no title).
When to use
- Filling a "page title" column next to a list of URLs
- Checking that a link still points at the page you expected
- Any script that needs the title without a full HTML parser
How to use this snippet
/**
* Return the page <title> for an http(s) URL, or '' if it cannot be read.
* Uses UrlFetchApp.fetch with muteHttpExceptions. Non-http(s) URLs,
* non-2xx/3xx responses, missing titles, and fetch errors all return ''.
* A few common HTML entities are decoded; this is not a full HTML parser.
*
* @param {string} url
* @return {string}
*/
function getPageTitle(url) {
var u = String(url == null ? '' : url).trim();
if (!/^https?:\/\//i.test(u)) return '';
var html = '';
try {
var resp = UrlFetchApp.fetch(u, { muteHttpExceptions: true, followRedirects: true });
var code = resp.getResponseCode();
if (code < 200 || code >= 400) return '';
html = String(resp.getContentText() || '');
} catch (e) {
return '';
}
var m = html.match(/<title\b[^>]*>([\s\S]*?)<\/title>/i);
if (!m) return '';
var title = String(m[1]).replace(/<[^>]+>/g, ' ');
title = title
.replace(/ /gi, ' ')
.replace(/&/gi, '&')
.replace(/</gi, '<')
.replace(/>/gi, '>')
.replace(/"/gi, '"')
.replace(/'|'/gi, "'")
.replace(/&#x([0-9a-f]+);/gi, function (_, n) {
return String.fromCharCode(parseInt(n, 16));
})
.replace(/&#(\d+);/g, function (_, n) {
return String.fromCharCode(Number(n));
});
return title.replace(/\s+/g, ' ').trim();
}
Example
function fillTitles() {
var sheet = SpreadsheetApp.getActive().getSheetByName('Links');
var last = sheet.getLastRow();
if (last < 2) return;
var urls = sheet.getRange(2, 1, last - 1, 1).getValues();
var out = urls.map(function (r) { return [getPageTitle(r[0])]; });
sheet.getRange(2, 2, out.length, 1).setValues(out);
}
Notes
- A
200page can still have a useless title ("Sign in", "Just a moment..."). This helper returns whatever is in the tag. - Redirects are followed. The title is from the final page.
- For HTTP status codes on a whole column, use Check Url Statuses instead of fetching each URL twice.
Happy Coding!
