【问题标题】:How to fix Lighthouse error: "Warning: Links are not crawlable"如何修复 Lighthouse 错误:“警告:链接不可抓取”
【发布时间】:2021-01-22 12:18:36
【问题描述】:

我在 Lighthouse 上测试了我的网站,但遇到了这个错误,有人知道如何解决吗?

链接不可抓取

这是我的代码分享社交媒体按钮

<a class="crunchify-link crunchify-facebook" 
href="https://www.facebook.com/sharer/sharer.php?u=&t=" 
title="Share on Facebook" 
rel="noopener" 
target="_blank" 
onclick="window.open('https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(document.URL) + '&t=' + encodeURIComponent(document.URL)); return false;"
>
    <div class="facebook-ic"></div>
</a>

【问题讨论】:

    标签: lighthouse


    【解决方案1】:

    您为什么收到此警告?

    Lighthouse 测试 onclick="window.open 以尝试捕获由 JavaScript 而非 href 激活的锚点,因为这不利于 SEO 和可访问性。

    修正/建议

    如果您的href 有效,我会说您可以放心地忽略它,但它无效(空的“u”和“t”参数)。

    修复您的href 使其有效(在服务器端构建它以填充ut 参数),您仍然会收到警告,但它可以安全然后忽略。

    虽然说如果您修复了 URL,那么 target="_blank" 将在新选项卡中打开共享器,这样就足够了,不需要任何 JavaScript。

    要删除错误,您应该将事件处理程序移动到 JavaScript 文件中,而不是使用内联 onclick 处理程序。

    这将在查看审计源代码后删除警告,是一种很好的做法。

    您可以使用target.addEventListener 轻松做到这一点。

    事件监听器的简单示例

        const el = document.getElementById("fbLink");
        el.addEventListener("click", sharerFunction, false);
    
        function sharerFunction(e){
            e.preventDefault();
            
            window.open('https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(document.URL) + '&t=' + encodeURIComponent(document.URL));
            alert("link will not open due to sandbox permissions, but check console it does fire");
        }
    &lt;a href="https://facebook.com" id="fbLink" ....**other stuff here**....&gt;Facebook icon&lt;/a&gt;

    相关部分审计源码供参考

    如前所述,source code for the crawlable-anchors test 显示了测试的内容,任何返回 true 的内容都是失败的,请注意 hasClickHandler 测试如何返回 null,因为这被认为是可以的(我相信,我可能已经晚了误读了代码!)。

      const windowLocationRegExp = /window\.location=/;
      const windowOpenRegExp = /window\.open\(/;
      const javaScriptVoidRegExp = /javascript:void(\(|)0(\)|)/;
    
      if (rawHref.startsWith('file:')) return true;
      if (windowLocationRegExp.test(onclick)) return true;
      if (windowOpenRegExp.test(onclick)) return true;
    
      const hasClickHandler = listeners.some(({type}) => type === 'click');
      if (hasClickHandler || name.length > 0) return;
    
      if (rawHref === '') return true;
      if (javaScriptVoidRegExp.test(rawHref)) return true;
    

    【讨论】:

      猜你喜欢
      • 2021-05-21
      • 2016-09-28
      • 1970-01-01
      • 1970-01-01
      • 2022-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多