如何知道用户何时离开页面并刷新页面 [英] How to know when a user has left the page and refreshed the page

查看:53
本文介绍了如何知道用户何时离开页面并刷新页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在用户离开页面之前进行AJAX调用(基本上在离开页面之前和刷新页面之前)?

I want to make an AJAX call before the user leaves the page (so basically before leaving the page and before refreshing the page)?

如何做到这一点。我试图用jQuery搜索一些东西,但没有得到任何东西。

How can this be done. I was trying to search something with jQuery but didnt get anything.

我尝试使用以下代码 -

I tried to use the following code -

window.onbeforeunload(function(){alert('before unload');});

但是离开页面(关闭浏览器选项卡)或刷新页面时,警报框永远不会出现。

But the alert box never appears when leaving the page(closing the browser tab) or refreshing the page.

如何实现?

推荐答案

$(window).unload(function() {
    alert('Visitor left page');
});

关于ajax调用,你可以这样做,但你必须设置 async false

Regarding the ajax call, you can do it, but you must set the async to false.

$.ajax({
   async: false,
   ...
 });

这篇关于如何知道用户何时离开页面并刷新页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆