【问题标题】:How to get description from a url?如何从 url 中获取描述?
【发布时间】:2020-12-20 03:51:27
【问题描述】:

您好,我正在创建一个 chrome 扩展,需要从 url 获取描述(如果有)。尝试寻找示例,但它们似乎仅适用于输入的硬数据 url。我从 content.js -->

获取我的网址
chrome.runtime.sendMessage({
  url: window.location.href
})

我现在想看看如何从该网址获取描述/元标记。任何提示或解决方案都会有所帮助。

【问题讨论】:

    标签: javascript jquery url google-chrome-extension metadata


    【解决方案1】:

    虽然document.head

    如果发现不错,您可能想先尝试描述,否则请查找 og:twitter: 标签。

    // title
    document.head.querySelector('title').innerText
    
    // normal description meta tag
    document.head.querySelector('meta[name="description"]').getAttribute('content')
    
    // twitter:
    document.head.querySelector('meta[name="twitter:description"]').getAttribute('content')
    
    // og:
    document.head.querySelector('meta[name="og:description"]').getAttribute('content')
    

    【讨论】:

    • 当我输入 document.head.querySelector('meta[name="description"]').getAttribute('content') 时,我收到“无法读取属性 'getAttribute' 的类型错误” of null ..”我会把我的网址放在某个特定的地方吗? @Lawrence Cherone
    • 如前所述,您需要检查它是否存在(几乎没有任何网站使用描述),拆分行,即删除 .getAttribute('content') 并检查 querySelector 没有返回 null,如果为 null尝试twitter:,如果为空,请尝试og:.. 不为空时使用getAttribute
    猜你喜欢
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多