extractMetaTags(html) reads a page's <title> and <meta> tags and returns an object with title, description, ogTitle, ogImage, and a camelCase key for every other name, property, or itemprop it finds (og:description becomes ogDescription, twitter:card becomes twitterCard). Missing core fields are empty strings. It does not fetch a URL — pass the HTML yourself, usually from UrlFetchApp.fetch.
When to use
- Replacing a cell of
IMPORTXMLthat sits on "Loading..." with a daily fetch that writes plain values - Filling title, description, and
og:imagecolumns next to a list of URLs - Inspecting the tags a page actually sent, before you trust a preview card
How to use this snippet
This is a small string parser, not a browser. It will not run JavaScript, so tags that only appear after a client-side render will be missing. It decodes a handful of HTML entities (&, , numeric entities) and collapses whitespace, the same way Get Page Title does.
/**
* Parse <title> and <meta> tags from an HTML string. Always returns
* title, description, ogTitle, and ogImage (empty string if missing),
* plus camelCase keys for other name/property/itemprop tags
* (og:description → ogDescription). First non-empty value wins.
* Does not fetch and does not throw on ordinary bad HTML.
*
* @param {string} html
* @return {Object}
*/
function extractMetaTags(html) {
var out = {
title: '',
description: '',
ogTitle: '',
ogImage: ''
};
var s = String(html == null ? '' : html);
var tm = s.match(/<title\b[^>]*>([\s\S]*?)<\/title>/i);
if (tm) out.title = decodeMeta_(String(tm[1]).replace(/<[^>]+>/g, ' '));
var re = /<meta\b[^>]*>/gi;
var m;
while ((m = re.exec(s))) {
var tag = m[0];
var content = metaAttr_(tag, 'content');
var charset = metaAttr_(tag, 'charset');
var key = metaAttr_(tag, 'property') || metaAttr_(tag, 'name') || metaAttr_(tag, 'itemprop');
if (charset && !out.charset) out.charset = decodeMeta_(charset);
if (!key) continue;
var camel = camelMeta_(key);
if (!camel) continue;
var value = decodeMeta_(content);
if (camel === 'title' && out.title) continue;
if (out[camel] == null || out[camel] === '') out[camel] = value;
}
return out;
}
function metaAttr_(tag, name) {
var re = new RegExp(
'\\b' + name + '\\s*=\\s*("([^"]*)"|\'([^\']*)\'|([^\\s>]+))',
'i'
);
var m = String(tag).match(re);
if (!m) return '';
return m[2] != null ? m[2] : m[3] != null ? m[3] : m[4] != null ? m[4] : '';
}
function camelMeta_(name) {
var s = String(name || '')
.trim()
.toLowerCase();
if (!s) return '';
s = s.replace(/[:._-]+([a-z0-9])/g, function (_, c) {
return c.toUpperCase();
});
return s.replace(/[^a-zA-Z0-9]+/g, '');
}
function decodeMeta_(s) {
var title = String(s == null ? '' : s);
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 refreshPageMeta() {
var sheet = SpreadsheetApp.getActive().getSheetByName('Pages');
var last = sheet.getLastRow();
if (last < 2) return;
var urls = sheet.getRange(2, 1, last - 1, 1).getDisplayValues(); // A = URL
var out = [];
for (var i = 0; i < urls.length; i++) {
var url = String(urls[i][0] || '').trim();
if (!url) {
out.push(['', '', '', '']);
continue;
}
var resp = UrlFetchApp.fetch(url, {
muteHttpExceptions: true,
followRedirects: true
});
var code = resp.getResponseCode();
if (code < 200 || code >= 400) {
out.push([code, '', '', '']);
continue;
}
var meta = extractMetaTags(resp.getContentText());
out.push([code, meta.title, meta.description, meta.ogImage]);
}
sheet.getRange(2, 2, out.length, 4).setValues(out); // B–E
}
The script needs the script.external_request scope. Write values, not IMPORTXML formulas, so the cells stay filled after the fetch.
Notes
- Attribute order and single or double quotes are fine (
contentbeforenameis common). - A
<title>tag wins over<meta name="title">. Other keys keep the first non-empty value. UrlFetchAppcounts against your daily URL Fetch quota. For a long list, see Budget Apps Script quotas like a grown-up and Retry UrlFetch with Backoff.
Happy Coding!
