单击外部链接时发出警告

时间:2021-02-26 13:33:57

标签: javascript html jquery css hyperlink

我想在点击外部页面时警告用户,但除了像这样的弹出窗口之外还有其他解决方案吗:Not wanted example

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

以下是来自不同站点的一个工作示例:Working example

谢谢!

1 个答案:

答案 0 :(得分:0)

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

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

相关问题