Programing

브라우저에서 뒤로 버튼 클릭 감지

lottogame 2020. 10. 24. 09:25
반응형

브라우저에서 뒤로 버튼 클릭 감지


이 질문에 이미 답변이 있습니다.

사용자가 뒤로 버튼을 클릭했는지 여부를 감지해야합니다. 이것을 위해 나는 사용하고 있습니다

window.onbeforeunload = function (e) {
}

사용자가 뒤로 버튼을 클릭하면 작동합니다. 하지만이 이벤트는 사용자가 F5를 클릭하거나 브라우저의 새로 고침 버튼을 클릭하면 발생합니다. 이 문제를 어떻게 해결합니까?


AJAX에 관한 한 ...

페이지의 특정 부분을 탐색하기 위해 AJAX를 사용하는 대부분의 웹 앱을 사용하는 동안 뒤로 누르는 것은 큰 문제입니다. 나는 '버튼을 비활성화한다는 것은 당신이 뭔가 잘못하고 있다는 것을 의미한다'는 것을 받아들이지 않으며, 사실 다른 측면의 개발자들은이 문제에 오랫동안 부딪 혔습니다. 내 해결책은 다음과 같습니다.

window.onload = function () {
    if (typeof history.pushState === "function") {
        history.pushState("jibberish", null, null);
        window.onpopstate = function () {
            history.pushState('newjibberish', null, null);
            // Handle the back (or forward) buttons here
            // Will NOT handle refresh, use onbeforeunload for this.
        };
    }
    else {
        var ignoreHashChange = true;
        window.onhashchange = function () {
            if (!ignoreHashChange) {
                ignoreHashChange = true;
                window.location.hash = Math.random();
                // Detect and redirect change here
                // Works in older FF and IE9
                // * it does mess with your hash symbol (anchor?) pound sign
                // delimiter on the end of the URL
            }
            else {
                ignoreHashChange = false;   
            }
        };
    }
}

내가 이것이 크롬, 파이어 폭스에서 작동한다고 말할 수있는 한 아직 IE를 테스트하지 않았습니다 .


이것을 시도하십시오 (브라우저가 "onbeforeunload"를 지원하지 않는 경우) :

jQuery(document).ready(function($) {

  if (window.history && window.history.pushState) {

    $(window).on('popstate', function() {
      var hashLocation = location.hash;
      var hashSplit = hashLocation.split("#!/");
      var hashName = hashSplit[1];

      if (hashName !== '') {
        var hash = window.location.hash;
        if (hash === '') {
          alert('Back button was pressed.');
        }
      }
    });

    window.history.pushState('forward', null, './#forward');
  }

});

내가 아는 가장 좋은 방법

         window.onbeforeunload = function (e) {
            var e = e || window.event;
            var msg = "Do you really want to leave this page?"

            // For IE and Firefox
            if (e) {
                e.returnValue = msg;
            }

            // For Safari / chrome
            return msg;
         };

이 방법으로 뒤로 버튼을 감지하고 있습니다.

window.onload = function () {
if (typeof history.pushState === "function") {
    history.pushState("jibberish", null, null);
    window.onpopstate = function () {
        history.pushState('newjibberish', null, null);
        // Handle the back (or forward) buttons here
        // Will NOT handle refresh, use onbeforeunload for this.
    };
}

작동하지만 쿠키로 제어하지 않고 페이지에 들어가면 브라우저가 뒤로 버튼을 클릭하지 않고 뒤로 작업을 수행하기 때문에 처음 페이지에 있음을 감지하기 위해 Chrome에서 쿠키를 만들어야합니다.

if (typeof history.pushState === "function"){
history.pushState("jibberish", null, null); 
window.onpopstate = function () {
    if ( ((x=usera.indexOf("Chrome"))!=-1) && readCookie('cookieChrome')==null ) 
    {
        addCookie('cookieChrome',1, 1440);      
    } 
    else 
    {
        history.pushState('newjibberish', null, null);  
    }
};

}

그리고 매우 중요 history.pushState("jibberish", null, null);합니다. 브라우저 기록을 복제합니다.

누가 그것을 고칠 수 있는지 아는 사람이 있습니까?


뒤로 버튼은 브라우저의 기능이므로 기본 기능을 변경하기 어려울 수 있습니다. 그래도 몇 가지 해결 방법이 있습니다. 이 기사를 살펴보십시오.

http://www.irt.org/script/311.htm

Typically, the need to disable the back button is a good indicator of a programming issue/flaw. I would look for an alternative method like setting a session variable or a cookie that stores whether the form has already been submitted.


I'm assuming that you're trying to deal with Ajax navigation and not trying to prevent your users from using the back button, which violates just about every tenet of UI development ever.

Here's some possible solutions: JQuery History Salajax A Better Ajax Back Button

참고URL : https://stackoverflow.com/questions/6359327/detect-back-button-click-in-browser

반응형