在浏览器选项卡上调用JS函数关闭 [英] Calling JS functions on browser tab close
问题描述
当用户关闭浏览器选项卡时,我需要调用JS函数。问题是我希望只有当用户关闭浏览器时才会发生这种情况。无需进行页面刷新,链接导航,表单提交和后退按钮按下。到目前为止我尝试了下面的jquery代码。
I need to call a JS function when user closing the browser tab. the problem is i want to happen this only when user closing the browser. no need to happen for page refresh, link navigation,form submit and back button press. i tried the below jquery code so far.
$(window).bind(
"beforeunload",
function() {
alert("don't close me");
return false;
}
)
$('form').submit(function() {
jQuery(window).unbind("beforeunload");
});
无效。任何人都可以为此回答。有什么其他js工具比jquery可用吗?。
its not working. can anyone answer for this. is there any other js tools than jquery available for this?.
如果我调用我的函数beforeunload事件,上面的消息即将到来。我不想显示此消息,我的功能必须工作。我尝试给e.preventDefault。但是当我使用它时,它也没有调用我的功能。任何人都可以提出建议。
谢谢。
And if i call my function "beforeunload" event, above message is coming. i don't want to show this message and my function has to be worked. i tried by giving e.preventDefault. but it's not calling my function also when i used that. can anybody suggest something. Thanks.
推荐答案
我同意这是一个不好的做法的评论,但我无法抗拒打电话试图回答问题。
I agree with the comments that this is a bad practice, but I can't resist the call to attempt answering the question.
我能想到的唯一方法是使用 onbeforeunload
,你已经在做什么了。但是,当有人通过其他方式离开页面时,您需要一种方法来禁用该警报。
The only way I can think of to accomplish this is to use onbeforeunload
, which you're already doing. But you need a way of disabling that alert when someone navigates away from the page by some other means.
var show_close_alert = true;
$("a").bind("mouseup", function() {
show_close_alert = false;
});
$("form").bind("submit", function() {
show_close_alert = false;
});
$(window).bind("beforeunload", function() {
if (show_close_alert) {
return "Killing me won't bring her back...";
}
});
这不是万无一失的,因为有很多方法可以在不看警报的情况下关闭浏览器(比如点击一下)链接,立即点击停止,然后关闭浏览器),但它可能会尽可能接近。
It's not foolproof, as in there are ways to close the browser without seeing the alert (like clicking a link, hitting Stop immediately, and then closing the browser), but it may be as close as you can get.
这是一个小提琴。
但请...不要这样做。
But please... don't do this.
这篇关于在浏览器选项卡上调用JS函数关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!