gpt4 book ai didi

javascript - javascript+onbeforeunload

转载 作者:行者123 更新时间:2023-11-30 13:42:58 25 4
gpt4 key购买 nike

我正在创建一个网络应用程序,在登录用户导航到主页后,我有一个导航栏(链接到页面/url)。导航栏是这样的主页-导航到主页个人资料 - 导航到个人资料页面聊天 - 当用户点击聊天链接时导航到聊天页面。我希望当用户意外或手动关闭浏览器窗口时,他应该收到警告,因为我使用了这样的 onbeforeunload 函数

 <script language="JavaScript">
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
</script>

现在,当我在聊天页面上关闭浏览器时,我收到以下警告“您已尝试离开此页面。”这工作正常,但现在的主要问题是当我点击其他链接时ProfileHome 这个函数被调用,我收到这个警报,即使我已经在 chat.jsp 中实现了这个代码。即使我刷新这个页面我收到上面提到的这个警报,只有当我关闭 chat.jsp 页面的窗口而不是其他页面或 Refresh.Plese 帮助

最佳答案

Onbeforeunload 在通过刷新、导航或页面关闭卸载页面时触发。您可以将 onclick 事件处理程序添加到页面上的 anchor 以删除您的 onbeforeunload 事件以避免它,并且您可以对窗口/正文/页面上的 onkeydown 事件执行相同的操作但是我不相信有一种方法可以捕捉用户按下浏览器的刷新按钮。

例子:

<html>
<head>
<script type="text/javascript">
function warnUnload(){
return "Your message here...";
}

function linkNavi(){
window.onbeforeunload = null;
}

function isRefresh(e){
var key = null;
if(window.event) // IE
key = e.keyCode;
else if(e.which) // Netscape/Firefox/Opera
key = e.which;

if(key == 116) //F5
window.onbeforeunload = null;
}

window.onbeforeunload = warnUnload;
window.onkeydown = isRefresh;
</script>
</head>
<body>
<a href="http://google.com">Google</a>
<a href="/" onclick="return linkNavi();">Home</a>
</body>
</html>

关于javascript - javascript+onbeforeunload,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1250559/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com