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

时间:2022-06-15 05:46:44

How might I capture the page reload event?

如何捕获页面重载事件?

I have a messaging system which loses all its input when the user refreshes the page. I want to use ajax to re-populate, hence my need to detect when the page has been refreshed/reloaded.

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

4 个解决方案

#1


33  

$('body').bind('beforeunload',function(){
   //do something
});

But this wont save any info for later, unless you were planning on saving that in a cookie somewhere (or local storage) and the unload event does not always fire in all browsers.

但这不会为以后保存任何信息,除非您打算将其保存在某个地方(或本地存储)的cookie中,而卸载事件并不总是在所有浏览器中发生。


Example: http://jsfiddle.net/maniator/qpK7Y/

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

Code:

代码:

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

     //save info somewhere

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

});

#2


12  

if you want to bookkeep some variable before page refresh

如果你想在页面刷新之前收藏一些变量

$(window).on('beforeunload', function(){
    // your logic here
});

if you want o load some content base on some condition

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

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

#3


8  

All the code is client side, I hope you fine this helpful:

所有的代码都是客户端代码,我希望您能理解这一点:

First thing there are 3 functions we will use:

首先,我们将使用三个功能:

    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;';
        }

Now we will start with the page load:

现在我们从页面载入开始:

$(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);
 }
})

#4


0  

There are two events on client side as given below.

客户端有两个事件,如下所示。

1. window.onbeforeunload (calls on Browser/tab Close & Page Load)

1。窗口。onbeforeunload(在浏览器/标签关闭和页面加载上调用)

2. window.onload (calls on Page Load)

2。窗口。onload(在页面加载上调用)

On server Side

在服务器端

public JsonResult TestAjax( string IsRefresh)
    {
        JsonResult result = new JsonResult();
        return result = Json("Called", JsonRequestBehavior.AllowGet);
    }

On Client Side

在客户端

 <script type="text/javascript">
    window.onbeforeunload = function (e) {
        
        $.ajax({
            type: 'GET',
            async: false,
            url: '/Home/TestAjax',
            data: { IsRefresh: 'Close' }
        });
    };

    window.onload = function (e) {

        $.ajax({
            type: 'GET',
            async: false,
            url: '/Home/TestAjax',
            data: {IsRefresh:'Load'}
        });
    };
</script>

On Browser/Tab Close: if user close the Browser/tab, then window.onbeforeunload will fire and IsRefresh value on server side will be "Close".

在浏览器/标签关闭:如果用户关闭浏览器/标签,那么窗口。onbeforeunload将触发,服务器端IsRefresh值将“关闭”。

On Refresh/Reload/F5: If user will refresh the page, first window.onbeforeunload will fire with IsRefresh value = "Close" and then window.onload will fire with IsRefresh value = "Load", so now you can determine at last that your page is refreshing.

在刷新/重载/F5:如果用户要刷新页面,第一个窗口。onbeforeunload将使用IsRefresh value =“Close”触发,然后打开窗口。onload将使用IsRefresh值= "Load",所以现在您可以确定您的页面刷新了。

#1


33  

$('body').bind('beforeunload',function(){
   //do something
});

But this wont save any info for later, unless you were planning on saving that in a cookie somewhere (or local storage) and the unload event does not always fire in all browsers.

但这不会为以后保存任何信息,除非您打算将其保存在某个地方(或本地存储)的cookie中,而卸载事件并不总是在所有浏览器中发生。


Example: http://jsfiddle.net/maniator/qpK7Y/

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

Code:

代码:

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

     //save info somewhere

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

});

#2


12  

if you want to bookkeep some variable before page refresh

如果你想在页面刷新之前收藏一些变量

$(window).on('beforeunload', function(){
    // your logic here
});

if you want o load some content base on some condition

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

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

#3


8  

All the code is client side, I hope you fine this helpful:

所有的代码都是客户端代码,我希望您能理解这一点:

First thing there are 3 functions we will use:

首先,我们将使用三个功能:

    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;';
        }

Now we will start with the page load:

现在我们从页面载入开始:

$(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);
 }
})

#4


0  

There are two events on client side as given below.

客户端有两个事件,如下所示。

1. window.onbeforeunload (calls on Browser/tab Close & Page Load)

1。窗口。onbeforeunload(在浏览器/标签关闭和页面加载上调用)

2. window.onload (calls on Page Load)

2。窗口。onload(在页面加载上调用)

On server Side

在服务器端

public JsonResult TestAjax( string IsRefresh)
    {
        JsonResult result = new JsonResult();
        return result = Json("Called", JsonRequestBehavior.AllowGet);
    }

On Client Side

在客户端

 <script type="text/javascript">
    window.onbeforeunload = function (e) {
        
        $.ajax({
            type: 'GET',
            async: false,
            url: '/Home/TestAjax',
            data: { IsRefresh: 'Close' }
        });
    };

    window.onload = function (e) {

        $.ajax({
            type: 'GET',
            async: false,
            url: '/Home/TestAjax',
            data: {IsRefresh:'Load'}
        });
    };
</script>

On Browser/Tab Close: if user close the Browser/tab, then window.onbeforeunload will fire and IsRefresh value on server side will be "Close".

在浏览器/标签关闭:如果用户关闭浏览器/标签,那么窗口。onbeforeunload将触发,服务器端IsRefresh值将“关闭”。

On Refresh/Reload/F5: If user will refresh the page, first window.onbeforeunload will fire with IsRefresh value = "Close" and then window.onload will fire with IsRefresh value = "Load", so now you can determine at last that your page is refreshing.

在刷新/重载/F5:如果用户要刷新页面,第一个窗口。onbeforeunload将使用IsRefresh value =“Close”触发,然后打开窗口。onload将使用IsRefresh值= "Load",所以现在您可以确定您的页面刷新了。