LoginSignup
80
56

More than 3 years have passed since last update.

JavaScriptでURLからOGP取得する

Last updated at Posted at 2019-10-28

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
80
56
3

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
  3. You can use dark theme
What you can do with signing up
80
56