developer tip

JavaScript를 사용하여 웹 페이지를 탐색하지 못하도록 방지

optionbox 2020. 7. 27. 07:50
반응형

JavaScript를 사용하여 웹 페이지를 탐색하지 못하도록 방지


JavaScript를 사용하여 웹 페이지를 탐색하지 못하게하는 방법은 무엇입니까?


를 사용하면 onunload메시지를 표시 할 수 있지만 탐색이 중단되지는 않습니다 (너무 늦어서). 그러나 사용할 수 있으며 onbeforeunload탐색이 중단됩니다.

window.onbeforeunload = function() {
  return "Are you sure you want to navigate away?";
}

편집 : confirm()예상대로 확인 창이 발생했지만 첫 번째 확인 결과와 함께 두 번째 확인이 표시되어 return 문에서 제거 되었습니다.


여기에 제시된 다른 방법들과 달리,이 비트 는 브라우저가 사용자에게 떠나고 싶은지를 묻는 경고를 표시 하지 않습니다 . 대신, 브라우저가 메모리에서 메모리를 언로드하기 전에 DOM의 이벤트 특성을 이용하여 현재 페이지로 다시 리디렉션하여 탐색을 취소합니다.

탐색을 직접 단락시켜 작동하므로 페이지가 닫히는 것을 막을 수 없습니다. 그러나 프레임 버스 팅을 비활성화하는 데 사용할 수 있습니다.

(function () {
    var location = window.document.location;

    var preventNavigation = function () {
        var originalHashValue = location.hash;

        window.setTimeout(function () {
            location.hash = 'preventNavigation' + ~~ (9999 * Math.random());
            location.hash = originalHashValue;
        }, 0);
    };

    window.addEventListener('beforeunload', preventNavigation, false);
    window.addEventListener('unload', preventNavigation, false);
})();

면책 조항 : 당신은 이것을해서는 안됩니다. 페이지에 프레임 버스 팅 코드가있는 경우 작성자의 희망을 존중하십시오.


이 약간 다른 버전으로 끝났습니다.

var dirty = false;
window.onbeforeunload = function() {
    return dirty ? "If you leave this page you will lose your unsaved changes." : null;
}

다른 곳에서는 폼이 더러워지면 dirty 플래그를 true로 설정했습니다 (또는 다른 방법으로 탐색을 방지하고 싶습니다). 이를 통해 사용자에게 탐색 확인 프롬프트가 표시되는지 여부를 쉽게 제어 할 수 있습니다.

선택한 답변의 텍스트와 함께 중복 프롬프트가 표시됩니다.

여기에 이미지 설명을 입력하십시오


Ayman의 예제에서 false를 반환하면 브라우저 창 / 탭이 닫히지 않습니다.

window.onunload = function () {
  alert('You are trying to leave.');
  return false;
}

최신 addEventListener API를 사용하는보다 최신의 브라우저 호환 방식과 동일합니다.

window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "\o/";

  e.returnValue = confirmationMessage;     // Gecko and Trident
  return confirmationMessage;              // Gecko and WebKit
});

Source: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload


The equivalent to the accepted answer in jQuery 1.11:

$(window).on("beforeunload", function () {
    return "Please don't leave me!";
});

JSFiddle example

altCognito's answer used the unload event, which happens too late for JavaScript to abort the navigation.


Use onunload.

For jQuery, I think this works like so:

$(window).unload(function() { 
  alert("Unloading"); 
  return falseIfYouWantToButBeCareful();
});

That suggested error message may duplicate the error message the browser already displays. In chrome, the 2 similar error messages are displayed one after another in the same window.

In chrome, the text displayed after the custom message is: "Are you sure you want to leave this page?". In firefox, it does not display our custom error message at all (but still displays the dialog).

A more appropriate error message might be:

window.onbeforeunload = function() {
    return "If you leave this page, you will lose any unsaved changes.";
}

또는 stackoverflow 스타일 : "게시물을 쓰거나 편집하기 시작했습니다."


브라우저의 뒤로 / 앞으로 버튼을 잡고 있고 탐색하고 싶지 않은 경우 다음을 사용할 수 있습니다.

window.addEventListener('popstate', function() {
    if (window.location.origin !== 'http://example.com') {
        // Do something if not your domain
    } else if (window.location.href === 'http://example.com/sign-in/step-1') {
        window.history.go(2); // Skip the already-signed-in pages if the forward button was clicked
    } else if (window.location.href === 'http://example.com/sign-in/step-2') {
        window.history.go(-2); // Skip the already-signed-in pages if the back button was clicked
    } else {
        // Let it do its thing
    }
});

그렇지 않으면 beforeunload 이벤트를 사용할 수 있지만 메시지가 브라우저 간 작동하거나 작동하지 않을 수 있으며 내장 프롬프트를 강제로 실행하는 항목을 리턴해야합니다.

참고 URL : https://stackoverflow.com/questions/821011/prevent-a-webpage-from-navigating-away-using-javascript

반응형