javascript - 单击外部链接时发出警告
问题描述
我想在点击外部页面时警告用户,但除了弹出窗口之外还有其他解决方案:
上面不需要的示例的代码<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/右键单击在新窗口中打开链接的情况。大多数必须通知用户这是外部链接的组织只是在外部链接旁边添加了一个图标。
推荐阅读
- c# - 如何在 C# 中检查 2 或 3 个应用程序是否打开并处于活动状态
- java - Oracle JDBC Thin:强制网络加密
- sharepoint-online - 如何使用 Power 自动化或 Rest API 向 SharePoint 文档库/列表上的用户授予访问权限
- r - 绘制统计功效与重复并计算系数的平均值
- python - 忽略命令中的异常无:discord.ext.commands.errors.CommandNotFound:找不到命令“加入”错误
- mysql - 使用 MySQL REGEXP 通过 Django ORM 过滤字符串
- plotly-dash - 从回调中选择数据表活动/选定单元格
- javascript - 在多行js字符串中插入重音
- javascript - React Hooks - useFetch 泛化
- python - 损失的不对称函数