Development Tip

탭 / 브라우저 닫기 전 확인

yourdevel 2020. 11. 27. 21:30
반응형

탭 / 브라우저 닫기 전 확인


Gmail에서와 같이 페이지를 떠나기 전에 사용자에게 확인을 요청하는 방법은 무엇입니까?

이 질문을 여러 곳에서 검색했지만 그들이 언급하는 것은 javascript window.unload & window.onbeforeunload 사용입니다 . 또한 차단되기 때문에 대부분의 경우 크롬에서 작동하지 않습니다.


이 시도:

<script>
window.onbeforeunload = function (e) {
    e = e || window.event;

    // For IE and Firefox prior to version 4
    if (e) {
        e.returnValue = 'Sure?';
    }

    // For Safari
    return 'Sure?';
};
</script>

다음은 작동하는 jsFiddle입니다.


이 시도:

<script>
    window.onbeforeunload = function(e) {
       return 'Dialog text here.';
    };
</script>

여기에 더 많은 정보 MDN .


Okay로 설정된 답변에 대한 의견을 읽었습니다 . 대부분의 사용자는 버튼과 일부 링크 클릭을 허용해야한다고 요청합니다. 여기에서 작동 할 기존 코드에 한 줄이 더 추가됩니다.

<script type="text/javascript">
  var hook = true;
  window.onbeforeunload = function() {
    if (hook) {

      return "Did you save your stuff?"
    }
  }
  function unhook() {
    hook=false;
  }

허용하려는 버튼 및 링크에 대해 unhook () onClick을 호출합니다.

<a href="#" onClick="unhook()">This link will allow navigation</a>

간단히

function goodbye(e) {
        if(!e) e = window.event;
        //e.cancelBubble is supported by IE - this will kill the bubbling process.
        e.cancelBubble = true;
        e.returnValue = 'You sure you want to leave?'; //This is displayed on the dialog

        //e.stopPropagation works in Firefox.
        if (e.stopPropagation) {
            e.stopPropagation();
            e.preventDefault();
        }
    }
window.onbeforeunload=goodbye;

조건에 따라 물어보고 싶은 경우 :

var ask = true
window.onbeforeunload = function (e) {
    if(!ask) return null
    e = e || window.event;
    //old browsers
    if (e) {e.returnValue = 'Sure?';}
    //safari, chrome(chrome ignores text)
    return 'Sure?';
};

참고URL : https://stackoverflow.com/questions/10311341/confirmation-before-closing-of-tab-browser

반응형