单击外部链接时发出警告

Warn when clicking external links

我想在点击外部页面时警告用户,但是有没有像这样的弹出窗口以外的解决方案:

上面不需要的例子的代码<a href="..." onclick="return confirm('You\'re about to leave this site. Are you sure?')">External Link</a>?

这是来自不同站点的工作示例:

谢谢!

您基本上必须捕获所有点击并检查它们是否在锚点和不同的域上。

document.body.addEventListener("click", function(evt) {
  evt.preventDefault();
  var anchor = evt.target.closest("a")
  if (anchor && anchor.href && anchor.host !== window.location.host) {
    document.querySelector(".message").classList.add("active");
    window.setTimeout(function () {
      window.location.href = anchor.href;
    }, 5000);
  }
});
.message {
  display: none;
}

.message.active {
  display: block;
  position: absolute;
  width: 200px;
  height: 100px;
  background-color: red;
}
<a href="https://www.example.com">Example</a>
<a href="/">Same Domain</a>

<div class="message">
  Whatever you want to say.
</div>

仅供参考:此代码未处理他们使用 tab/shift/right 的情况,单击以在新的 window 中打开 link。大多数必须通知用户这是外部 link 的组织只是在外部 link 旁边添加了一个图标。