如何在浏览器关闭时触发jQuery

发布于 2024-12-18 22:06:35 字数 318 浏览 0 评论 0原文

可能的重复:
javascript检测浏览器关闭选项卡/关闭浏览器

有谁知道可靠的方法监听 javascript/ jQuery 中的窗口关闭事件?

该窗口是父实例,而不是任何子实例。即,如果错误关闭了窗口,并且访问者再次启动浏览器并再次加载之前访问过的 URL。

Possible Duplicate:
javascript detect browser close tab/close browser

Does anyone know a reliable way to listen out for a window closing event in javascript/ jQuery?

The window is the parent and not any child instances. I.e. if a window is closed by mistake and the visitor launches their browser again and loads the url previously visited once more.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

残月升风 2024-12-25 22:06:35

您可以使用 window.unload 事件设置 cookie 或使用本地存储来使用 new.date() 保存时间,然后查看访问者是否在设定的时间内返回。

像这样的事情:

$(window).unload(function() {
    localStorage.setItem(“theyLeft”, new Date());
}

然后在加载时检查:

$(window).load(function() {
    var timeGoneBy = new Date() - localStorage.getItem(“theyLeft”);
    //calculate time gone by, and do something if visitor returned within given time etc.
}

需要大量改进,并且本地存储应该有 cookie 作为后备,但只是为了显示它的要点。

You can use the window.unload event to set a cookie or use local storage to save the time using new.date(), then see if the visitor returned within a set amount of time.

Something like:

$(window).unload(function() {
    localStorage.setItem(“theyLeft”, new Date());
}

then on load check for :

$(window).load(function() {
    var timeGoneBy = new Date() - localStorage.getItem(“theyLeft”);
    //calculate time gone by, and do something if visitor returned within given time etc.
}

Would need to be refined a lot, and local storage should have cookies as fallback, but just to show the jist of it.

谈情不如逗狗 2024-12-25 22:06:35

尝试卸载方法。

当用户导航时,卸载事件被发送到窗口元素
远离页面。这可能意味着许多事情之一。用户可以
单击链接离开页面,或在
地址栏。前进和后退按钮将触发该事件。
关闭浏览器窗口将导致该事件被触发。甚至
页面重新加载将首先创建卸载事件。

您还可以尝试使用 JS onunload 和 onbeforeunload 事件。

Try the unload method.

The unload event is sent to the window element when the user navigates
away from the page. This could mean one of many things. The user could
have clicked on a link to leave the page, or typed in a new URL in the
address bar. The forward and back buttons will trigger the event.
Closing the browser window will cause the event to be triggered. Even
a page reload will first create an unload event.

You can also try playing with the JS onunload and onbeforeunload events.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文