[英]The best way to implement window close event
Long story is short - I am trying to submit a certain form when user closes the window, or is not responding for 20min. 长话短说-当用户关闭窗口或20分钟没有响应时,我正在尝试提交某种表格。
The second I've done using this code: 我使用此代码完成的第二步:
timeOut = setTimeout(function () {
submitThisForm(document.forms.sendDealerInfo);
console.log("Timed out...");
}, 600000);
For the first one I've tried with this code: 对于第一个,我尝试使用此代码:
window.onbeforeunload = function() {
submitThisForm(document.forms.sendDealerInfo);
clearTimeout(timeOut);
return null;
}
Unfortunately window.onbeforeunload
event won't trigger in all browsers (in Chrome and Opera for example). 不幸的是window.onbeforeunload
事件不会在所有浏览器中触发(例如,在Chrome和Opera中)。 I also tried: $(window).unload(function () {...
and window.addEventListener("beforeunload", function (event) {...
But same story - they won't work in all browsers. 我也尝试过: $(window).unload(function () {...
和window.addEventListener("beforeunload", function (event) {...
但同样的故事-它们不能在所有浏览器中都起作用。
Is there a way to accomplish what I am trying to do some other way? 有没有办法完成我尝试做的其他事情? Perhaps with sessions? 也许有会议?
As Suman says, onBeforeUnload
is supported in all the major browsers. 正如Suman所说,所有主要浏览器都支持onBeforeUnload
。 But most, if not all, the browsers will not let you do anything within that event beyond returning a string for the "Are you sure you want to leave this page?" 但是,大多数(如果不是全部)浏览器将不允许您在该事件中执行任何操作,只能返回“您确定要离开此页面?”的字符串。 dialog. 对话。
Then with onUnload
you're attempting to submit a form after the page has already been unloaded, and navigation is already happening. 然后,使用onUnload
尝试在页面已被卸载并且导航已经开始之后提交表单。 It would be a very odd user experience to be navigating away then be redirected somewhere else. 导航然后被重定向到其他地方,将是非常奇怪的用户体验。
Trying to submit a form when the window is closed isn't a very safe method. 在关闭窗口时尝试提交表单并不是一种非常安全的方法。 The web browser could crash, the user could force close it, the internet connection could be interrupted, among other things. 网络浏览器可能崩溃,用户可能会强行关闭它,互联网连接可能会中断,等等。 I think your best bet would be to submit the form every so often. 我认为您最好的选择是经常提交表格。 Possibly detecting an idle timeout of a few seconds, then submitting your form? 可能检测到几秒钟的空闲超时,然后提交表单?
window.onbeforeunload
is works in all major browsers, Like it is supported from Chrome 1 and Opera 12 window.onbeforeunload
适用于所有主流浏览器,例如Chrome 1和Opera 12都支持window.onbeforeunload
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.