首页 > 解决方案 > 单击外部链接时发出警告

问题描述

我想在点击外部页面时警告用户,但除了弹出窗口之外还有其他解决方案:不想要的例子

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

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

谢谢!

标签: javascripthtmljquerycsshyperlink

解决方案


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

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/右键单击在新窗口中打开链接的情况。大多数必须通知用户这是外部链接的组织只是在外部链接旁边添加了一个图标。


推荐阅读