メタタグの情報(description,keywordsなど)を取得する【JavaScript】
公開日 更新日
この記事では、ページのメタタグの情報を取得する方法を紹介していきます。
descriptionやkeywordsなどのコンテンツが取得ができます。
まずは簡潔に取得するコードを紹介します。
記事後半で取得したい情報を指定して取得する方法を説明します。
また、タイトルタグの取得は「titleタグを取得する【JavaScript】」をご覧ください。
meta descriptionを取得する
まずはmeta descriptionを取得する方法です。
取得方法には色々ありますが、2パターン紹介します。
document.getElementsByName('description').item(0).content;
上記はgetElementsByNameを使う方法です。
document.querySelector('meta[name="description"]').content;
上記はquerySelectorを使う方法です。
しかし、いずれもdescriptionがない場合にはエラーが返ります。
エラーを避けたい場合は、オプショナルチェーン(?.)を使うと、descriptionがないときにエラーではなくundefinedが返ります。
document.querySelector('meta[name="description"]')?.content;
meta keywordsを取得する
次はmeta keywordsを取得します。
こちらも同様に2パターン紹介します。
document.getElementsByName('keywords').item(0).content;
上記はgetElementsByNameを使った方法です。
document.querySelector('meta[name="keywords"]').content;
上記はquerySelectorを使った方法です。
しかし、いずれもkeywordsがない場合にはエラーが返ります。(こちらも?.contentを使うとエラーを避けられます。)
なお、meta keywordsはGoogle検索では使われていません。SEOのために設定する必要はありませんが、メタ情報の取得方法の例として紹介しています。
metaタグを指定して取得する
あまり使う場面はないかもしれませんが、metaタグの属性を指定して取得する方法も載せます。
name属性を指定して取得
function getMeta(metaName) {
var metas = document.getElementsByTagName('meta');
for (let i = 0; i < metas.length; i++) {
if (metas[i].getAttribute('name') === metaName) {
return metas[i].getAttribute('content');
}
}
}
console.log(getMeta('description'));
property属性を指定して取得
function getMeta(metaProperty) {
var metas = document.getElementsByTagName('meta');
for (let j = 0; j < metas.length; j++) {
if (metas[j].getAttribute('property') === metaProperty) {
return metas[j].getAttribute('content');
}
}
}
console.log(getMeta('og:title'));