如何使用jquery检测页面刷新?

sis*_*sko 40 jquery events refresh reload

我如何捕获页面重新加载事件?

我有一个消息传递系统,当用户刷新页面时,它会丢失所有输入.我想使用ajax重新填充,因此我需要检测页面何时被刷新/重新加载.

Nea*_*eal 41

$('body').bind('beforeunload',function(){
   //do something
});
Run Code Online (Sandbox Code Playgroud)

但是这不会保存以后的任何信息,除非您计划将其保存在某个地方的cookie(或本地存储)中,并且unload事件并不总是在所有浏览器中触发.


示例:http: //jsfiddle.net/maniator/qpK7Y/

码:

$(window).bind('beforeunload',function(){

     //save info somewhere

    return 'are you sure you want to leave?';

});
Run Code Online (Sandbox Code Playgroud)

  • 为了记录,它也将在页面关闭时被触发. (12认同)
  • 这应该是"on"和"unload"吗?http://api.jquery.com/unload/ - 另外,这会检测到Firefox中的F5吗? (3认同)
  • 这也检测到浏览器上的后退按钮不仅仅是页面刷新. (2认同)

Uza*_*air 16

如果你想在页面刷新之前预订一些变量

$(window).on('beforeunload', function(){
    // your logic here
});
Run Code Online (Sandbox Code Playgroud)

如果你想在某些条件下加载一些内容

$(window).on('load', function(){
    // your logic here`enter code here`
});
Run Code Online (Sandbox Code Playgroud)


Arr*_*abi 9

所有的代码都是客户端的,我希望你这很好用这个:

首先,我们将使用3个函数:

    function setCookie(c_name, value, exdays) {
            var exdate = new Date();
            exdate.setDate(exdate.getDate() + exdays);
            var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
            document.cookie = c_name + "=" + c_value;
        }

    function getCookie(c_name) {
        var i, x, y, ARRcookies = document.cookie.split(";");
        for (i = 0; i < ARRcookies.length; i++) {
            x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
            y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
            x = x.replace(/^\s+|\s+$/g, "");
            if (x == c_name) {
                return unescape(y);
            }
        }
    }

    function DeleteCookie(name) {
            document.cookie = name + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
        }
Run Code Online (Sandbox Code Playgroud)

现在我们将从页面加载开始:

$(window).load(function () {
 //if IsRefresh cookie exists
 var IsRefresh = getCookie("IsRefresh");
 if (IsRefresh != null && IsRefresh != "") {
    //cookie exists then you refreshed this page(F5, reload button or right click and reload)
    //SOME CODE
    DeleteCookie("IsRefresh");
 }
 else {
    //cookie doesnt exists then you landed on this page
    //SOME CODE
    setCookie("IsRefresh", "true", 1);
 }
})
Run Code Online (Sandbox Code Playgroud)