ANa*_*imi 186 javascript
检测用户是否离开网页的最佳方法是什么?
在onunloadJavaScript事件,每次不工作(HTTP请求,而不是终止该浏览器所需要的时间需要更长的时间).
当前的浏览器可能会阻止创建一个.
And*_*son 214
尝试onbeforeunload事件:在卸载页面之前触发它.它还允许您回询用户是否真的要离开.查看演示onbeforeunload Demo.
或者,您可以在他离开时发出Ajax请求.
Duc*_*tro 16
Mozilla Developer Network有一个很好的描述和onbeforeunload的例子.
如果您想要在离开页面之前警告用户,如果您的页面是脏的(即,如果用户输入了一些数据):
window.addEventListener('beforeunload', function(e) {
var myPageIsDirty = ...; //you implement this logic...
if(myPageIsDirty) {
//following two lines will cause the browser to ask the user if they
//want to leave. The text of this dialog is controlled by the browser.
e.preventDefault(); //per the standard
e.returnValue = ''; //required for Chrome
}
//else: user is allowed to leave without a warning dialog
});
Run Code Online (Sandbox Code Playgroud)
suh*_*lvs 10
为此,我使用:
window.onbeforeunload = function (e) {
}
Run Code Online (Sandbox Code Playgroud)
它在页面卸载之前被触发.
这是另一种解决方案-由于在大多数浏览器中,导航控件(导航栏,标签等)都位于页面内容区域上方,因此您可以检测到鼠标指针从顶部离开页面并在显示“ 离开之前 ”对话。它完全不引人注目,它允许您在用户实际执行要离开的操作之前与其进行交互。
$(document).bind("mouseleave", function(e) {
if (e.pageY - $(window).scrollTop() <= 1) {
$('#BeforeYouLeaveDiv').show();
}
});
Run Code Online (Sandbox Code Playgroud)
不利的一面是,当然是用户实际上打算离开的猜测,但是在大多数情况下,这是正确的。
如果您需要执行一些异步代码(例如向服务器发送一条消息,表明用户现在没有关注您的页面),该事件beforeunload将不会给异步代码运行时间。在异步的情况下,我发现visibilitychange和mouseleaveevents 是最好的选择。当用户更改选项卡、隐藏浏览器或将课程器移出窗口范围时,会触发这些事件。
document.addEventListener('mouseleave', e=>{
//do some async code
})
document.addEventListener('visibilitychange', e=>{
if (document.visibilityState === 'visible') {
//report that user is in focus
} else {
//report that user is out of focus
}
})Run Code Online (Sandbox Code Playgroud)
我知道已经回答了这个问题,但是如果您只希望在关闭实际的BROWSER时(而不只是在发生页面加载时)触发某些内容,则可以使用以下代码:
window.onbeforeunload = function (e) {
if ((window.event.clientY < 0)) {
//window.localStorage.clear();
//alert("Y coords: " + window.event.clientY)
}
};
Run Code Online (Sandbox Code Playgroud)
在我的示例中,我正在清除本地存储并用鼠标y坐标警告用户,仅当关闭浏览器时,程序中所有页面加载时才会忽略此操作。
页面可见性API
\n\xe2\x9c\x85页面可见性 API 提供了一些事件,可以通过观察这些事件来了解文档何时变得可见或隐藏。
\n\xe2\x9c\x85当用户最小化窗口或切换到另一个选项卡时,API 会触发事件visibilitychange。
\xe2\x9c\x85我们可以根据visibilityState
function onVisibilityChange() {\n if (document.visibilityState === 'visible') {\n console.log("user is focused on the page")\n } else {\n console.log("user left the page")\n }\n}\n\ndocument.addEventListener('visibilitychange', onVisibilityChange);\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
177247 次 |
| 最近记录: |