使用 onclick 功能分享 Facebook 或 Line,但遇到 SEO 问题 "Links are not crawlable"

Share Facebook or Line with onclick function, but get SEO problem "Links are not crawlable"

我用 onclick 功能分享 Facebook 和 Line:


<a href="javascript:void(0);" onclick="window.open('http://www.facebook.com/share.php?u='.concat(encodeURIComponent(location.href)), '', 'menubar=no,toolbar=no,resizable=no,scrollbars=yes,height=700,width=550')" title="Facebook Share" aria-label="Facebook Share">

<a href="javascript:void(0);" onclick="window.open('http://line.naver.jp/R/msg/text/?Page title%0A'.concat(encodeURIComponent(location.href)),'Share with Line', config='height=700,width=550')" title="Line Share" aria-label="Line Share">

Google 灯塔结果:

Search engines may use href attributes on links to crawl websites. Ensure that the href attribute of anchor elements links to an appropriate destination, so more pages of the site can be discovered.

所以我不能使用 <a> 元素,如果想用新的 window 打开 link?

在这种特殊情况下,我会说您可以忽略该消息,从语义的角度来看,您使用的是正确的元素。

然而,您可以改进这一点(并消除错误)的一种方法是在服务器上预构建 URL,然后使用 JavaScript 侦听器拦截点击并打开新的 window.

最大的优势是你有一个有效的URL 你的JavaScript失败并且对SEO也有好处。

在下面的示例中,我已将 URL、window 名称和 window 设置移动到 link 上的 data 属性中。

然后我将完整的 URL 放入 href 属性中,没有所有 window 设置等

最后,我将事件处理程序附加到您的 link 拦截点击并启动 window。

请注意,由于 Stack Overflow 上的沙箱,您不能 运行 以下代码段,因此 check this fiddle instead.

var anchors = document.querySelectorAll('.sharer');

for(var z = 0; z < anchors.length; z++) {

anchors[z].addEventListener('click', function(e) {
//stop the default click action
  e.preventDefault();
// grab the base sharing URL
  var URL = e.target.getAttribute('data-url');
// grab the name we want to give the window (parameter 2 on window.open)
  var windowName = e.target.getAttribute('data-windowName');
// Grab parameter 3 for window.oprn (window settings)
  var windowSettings = e.target.getAttribute('data-settings');
// call window.open
  window.open(URL + window.location.href, windowName, windowSettings);
}, false);

}
<h2>Won't work on Stack Overflow due to sandbox so may need tweaking your side</h2>

<a class="sharer" href="http://www.facebook.com/share.php?u=" data-url="http://www.facebook.com/share.php?u=" data-windowName="" data-settings="menubar=no,toolbar=no,resizable=no,scrollbars=yes,height=700,width=550" title="Facebook Share" aria-label="Facebook Share">Facebook</a>

<a class="sharer" href="http://line.naver.jp/R/msg/text/?Page title%0A" data-url="http://line.naver.jp/R/msg/text/?Page title%0A" data-windowName="Share with Line"  data-settings="height=700,width=550" title="Line Share" aria-label="Line Share">Line</a>

<h2>fallback behaviour</h2>
<p>The below shows how the link behaves with no javascript</p>

<a href="http://www.facebook.com/share.php?u=" title="Facebook Share" aria-label="Facebook Share" target="_blank">Facebook</a>