복붙노트

[JQUERY] jQuery를 사용하여 페이지 새로 고침을 어떻게 감지합니까?

JQUERY

jQuery를 사용하여 페이지 새로 고침을 어떻게 감지합니까?

해결법


  1. 1.

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

    그러나 쿠키에 해당 쿠키에 저장 (또는 로컬 스토리지) 및 언로드 이벤트를 저장할 계획이 아니라면 모든 정보를 저장하지 않는 한 모든 브라우저에서 항상 해방되지 않습니다.

    예 : http://jsfiddle.net/maniator/qpk7y/

    암호:

    $(window).bind('beforeunload',function(){
    
         //save info somewhere
    
        return 'are you sure you want to leave?';
    
    });
    

  2. 2.페이지 새로 고침 전에 일부 변수를 북 키우기를 원한다면

    페이지 새로 고침 전에 일부 변수를 북 키우기를 원한다면

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

    일부 조건을 기반으로 일부 콘텐츠를로드하려면

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

  3. 3.모든 코드는 클라이언트 측입니다.이 도움이되기를 바랍니다.

    모든 코드는 클라이언트 측입니다.이 도움이되기를 바랍니다.

    먼저 우리가 사용할 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;';
            }
    

    이제 우리는 페이지로드로 시작합니다.

    $(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. 4.아래에 주어진 클라이언트 측에 두 가지 이벤트가 있습니다.

    아래에 주어진 클라이언트 측에 두 가지 이벤트가 있습니다.

    1. window.onbeforeUnload (브라우저 / 탭 닫기 및 페이지로드에서 호출)

    2. window.onload (페이지로드 호출)

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