開いているページのOGP情報を取得するブックマークレット
2022/02/02追記:プレビュー機能などを追加したChrome拡張機能を作りました。
一応ブックマークレットの使い方も書いておく。
- 適当なページをブックマークする。
- ブックマークの編集でURL欄に以下のコードを張り付ける。ChromeやEdge(Chromium版)で試した感じスペースや改行があっても動作には影響はない模様。
- OGP情報を取得したいページを開いて、ブックマークレットを実行する。
- クリップボードにJSON形式でOGP関連の情報がコピーされているのでテキストファイルなどに張り付ける。
クリップボードへのコピーにnavigator.clipboard.writeText
を使用しているのでHTTPS接続のページでしか使えない。
javascript: (() => {
fetch(location.href).then(r => r.text()).then(text => {
const head = Array.prototype.slice.call((new DOMParser().parseFromString(text, 'text/html')).head.children);
const title = head.find(e => e.tagName == 'TITLE').textContent;
const meta = head.filter(e => e.tagName == 'META' && (('name' in e.attributes) || ('property' in e.attributes)));
const description = meta.find(e => e.name == 'description').content;
const extract = (name, sign) => {
const r = {};
meta.filter(e => e.attributes[name] && !e.attributes[name].value.indexOf(sign)).map(e => { r[e.attributes[name].value.substr(sign.length)] = e.attributes.content.value });
return r;
};
const ogp = extract('property', 'og:');
const twitter = extract('name', 'twitter:');
const facebook = extract('property', 'fb:');
const result = { title, description };
const add = (o, name) => Object.values(o).length > 0 ? result[name] = o : null;
add(ogp, 'ogp');
add(twitter, 'twitter');
add(facebook, 'facebook');
navigator.clipboard.writeText(JSON.stringify(result)).then(() => alert('OGP tags copy successfully.'), () => alert('OGP tags copy failed.'));
})
})();