search
LoginSignup
50

More than 1 year has passed since last update.

posted at

updated at

JavaScriptでURLからOGP取得する

JavaScriptでURLからOGP取得します。

結論

const url = "https://qiita.com/ksyunnnn/items/bfe2b9c568e97bb6b494";

fetch(url).then(res => res.text()).then(text => {
    const el = new DOMParser().parseFromString(text, "text/html")
    const headEls = (el.head.children)
    Array.from(headEls).map(v => {
        const prop = v.getAttribute('property')
        if (!prop) return;
        console.log(prop, v.getAttribute("content"))
    })
})

結果

og:title JavaScriptでURLからOGP取得する - Qiita
og:type article
og:url https://qiita.com/ksyunnnn/items/bfe2b9c568e97bb6b494
og:image https://cdn.qiita.com/assets/qiita-fb-2887e7b4aad86fd8c25cea84846f2236.png
# 以下略

デベロッパーコンソールとかで適当に試してみてください

追記

リスト表示

fetch(url).then(res => res.text()).then(text => {
    const el = new DOMParser().parseFromString(text, "text/html")
    const headEls = (el.head.children)

    return Array.from(headEls).map(v => {
        const prop = v.getAttribute('property')
        if (!prop) return;
        return { prop: prop.replace("og:",""),content: v.getAttribute("content")}
    })
}).then(list=>{
    return list.filter(v=>v)
}).then(result=>console.log({result}))

SNS共有用に整形

const url = "https://qiita.com/ksyunnnn/items/bfe2b9c568e97bb6b494"

fetch(url).then(res => res.text()).then(text => {
    const el = new DOMParser().parseFromString(text, "text/html")
    const headEls = (el.head.children)

    return Array.from(headEls).map(v => {
        const prop = v.getAttribute('property')
        if (!prop) return;
        return { prop: prop.replace("og:",""),content: v.getAttribute("content")}
    })
}).then(list=>{
    return list.filter(v=>v)
}).then(result=>{
    const title = result.filter(v=>v.prop==="title")[0].content;
    const url = result.filter(v=>v.prop==="url")[0].content;
    console.log(`${title} | ${url}`)
})

// 結果
// JavaScriptでURLからOGP取得する - Qiita | https://qiita.com/ksyunnnn/items/bfe2b9c568e97bb6b494

いまみてるサイトから取得する

const url = location.href

fetch(url).then(res => res.text()).then(text => {
    const el = new DOMParser().parseFromString(text, "text/html")
    const headEls = (el.head.children)

    return Array.from(headEls).map(v => {
        const prop = v.getAttribute('property')
        if (!prop) return;
        return { prop: prop.replace("og:",""),content: v.getAttribute("content")}
    })
}).then(list=>{
    return list.filter(v=>v)
}).then(result=>{
    const title = result.filter(v=>v.prop==="title")[0].content;
    const url = result.filter(v=>v.prop==="url")[0].content;
    console.log(`${title} | ${url}`)
})

// 結果
// JavaScriptでURLからOGP取得する - Qiita | https://qiita.com/ksyunnnn/items/bfe2b9c568e97bb6b494

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
50