如何捕捉事件并区分关闭和刷新事件
how to catch the event and distinguish close and refresh event
在我的项目中,我需要在浏览器中使用关闭事件,通过web,服务器和数据库处理用户退出时的信息。我不知道如何捕捉事件和区分关闭和刷新事件。
我试了这些代码:
window.onbeforeunload = function() {
var n = window.event.screenX - window.screenLeft;
var b = n > document.documentElement.scrollWidth-20;
if(b && window.event.clientY < 0 || window.event.altKey) {
alert("close event");
}else{
alert("refresh event");
}
}
但是它只捕获刷新事件。有没有更好的办法来解决这个问题?
此外,我已经阅读了如何区分浏览器关闭和刷新事件在Chrome?
一个想法:通过cookie来判断是否登录。
而且浏览器通常不会禁用cookie。
如果cookie是禁用的,您可以要求用户启用它。
下面是一个cookie的例子:
function setCookie(name, value) //cookies setting
{
var argv = setCookie.arguments;
var argc = setCookie.arguments.length;
var expires = (argc > 2) ? argv[2] : null;
if(expires!=null)
{
var LargeExpDate = new Date ();
LargeExpDate.setTime(LargeExpDate.getTime() + (expires*1000*3600*24));
}
document.cookie = name +value }
//In Js
setCookie("a","34234523542");
//read cookie:
function WM_readCookie(name)
{
//if there is no cookie,return false;or get value and return value
if(document.cookie == '')
return false;
else
return
unescape(WM_getCookieValue(name));
}
function WM_getCookieValue(name)
{
// Declare variables.
var firstChar,lastChar;
// Get the entire cookie string.
// (This may have other
name=value pairs in it.)
var theBigCookie = document.cookie;
// Grab
just this cookie from theBigCookie string.
// Find the start of
'name'.
firstChar = theBigCookie.indexOf(name);
// If you found it,
if(firstChar != -1)
{
// skip 'name' and '='.
firstChar +=
name.length + 1;
// Find the end of the value string (i.e. the next
';').
lastChar = theBigCookie.indexOf(';', firstChar);
if(lastChar == -1) lastChar = theBigCookie.length;
// Return the
value.
return theBigCookie.substring(firstChar, lastChar);
} else
{
// If there was no cookie, return false.
return false;
}
}
相关文章:
- 如何防止jQueryonclick事件中的Ruby方法在页面刷新时执行
- 如何刷新列表框内容onclick或blur事件
- 检测window.opener窗口刷新事件
- 如何在不刷新的情况下停止类的事件
- 当至少有一个用户触发事件而不刷新页面时,更改所有用户页面中的内容
- 是否有任何事件“;在$scope摘要完成时”;或“;在视图刷新时”;在Angular.js中
- socket.io”;“连接”;刷新/重新加载时的事件不会激发
- JQuery没有't在“t”上注册事件;刷新”;元素
- 如何刷新事件处理程序中的ODataModel
- Jquery Mobile Onclick事件在刷新前不起作用
- 正在努力解决如何刷新事件侦听器
- 如何防止刷新页面时加载点击事件
- HTML-JavaScript:每当触发事件时,页面都会刷新
- 想要禁用浏览器的刷新事件
- 服务器发送事件未正确(刷新?)使用Flask和Redis与nginx前端
- 为什么 JavaScript 事件刷新页面
- 使用OnBeforeUnload事件刷新浏览器
- 使用select onchange事件刷新jquery滑块
- 根据所有选项卡共有的事件刷新当前选项卡内容
- dom事件-刷新后的JavaScript评级