您为什么收到此警告?
Lighthouse 测试 onclick="window.open 以尝试捕获由 JavaScript 而非 href 激活的锚点,因为这不利于 SEO 和可访问性。
修正/建议
如果您的href 有效,我会说您可以放心地忽略它,但它无效(空的“u”和“t”参数)。
修复您的href 使其有效(在服务器端构建它以填充u 和t 参数),您仍然会收到警告,但它可以安全然后忽略。
虽然说如果您修复了 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");
}
<a href="https://facebook.com" id="fbLink" ....**other stuff here**....>Facebook icon</a>
相关部分审计源码供参考
如前所述,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;