programing

"이 페이지에서 벗어나시겠습니까?"를 표시하는 방법" 변경은 언제 커밋됩니까?

javaba 2022. 11. 5. 11:32
반응형

"이 페이지에서 벗어나시겠습니까?"를 표시하는 방법" 변경은 언제 커밋됩니까?

stackoverflow에서 변경을 시작한 후 페이지에서 벗어나려고 하면 Javascript 확인 버튼이 나타나 "이 페이지에서 벗어나시겠습니까?"라고 묻습니다.

이전에 이를 구현한 적이 있는 사람이 있습니까? 변경이 커밋된 것을 추적하려면 어떻게 해야 합니까?제가 직접 할 수 있을 것 같아요. 전문가 여러분들로부터 좋은 관행을 배우려고 노력 중입니다.

다음을 시도했지만 여전히 작동하지 않습니다.

<html>
<body>
    <p>Close the page to trigger the onunload event.</p>
    <script type="text/javascript">
        var changes = false;        
        window.onbeforeunload = function() {
            if (changes)
            {
                var message = "Are you sure you want to navigate away from this page?\n\nYou have started writing or editing a post.\n\nPress OK to continue or Cancel to stay on the current page.";
                if (confirm(message)) return true;
                else return false;
            }
        }
    </script>

    <input type='text' onchange='changes=true;'> </input>
</body>
</html>

예시를 올릴 수 있는 사람?

갱신(2017년)

현재 최신 브라우저에서는 사용자 지정 메시지 표시를 보안 위험으로 간주하고 있으므로 모든 브라우저에서 제거되었습니다.브라우저는 이제 일반 메시지만 표시합니다.메시지 설정에 대해 걱정할 필요가 없어졌기 때문에 다음과 같이 간단합니다.

// Enable navigation prompt
window.onbeforeunload = function() {
    return true;
};
// Remove navigation prompt
window.onbeforeunload = null;

레거시 브라우저 지원에 대해서는, 이하를 참조해 주세요.

갱신(2013년)

orginal answer는 IE6-8 및 FX1-3.5(2009년 작성 당시 목표로 하고 있던 것)에 적합하지만, 현재는 다소 구식이며, 최신 브라우저에서는 동작하지 않습니다.참고를 위해 아래에 남겨두었습니다.

window.onbeforeunload는 모든 브라우저에서 일관되게 처리되지 않습니다.(만, 대부분의 는 에 합니다.onbeforeunload)null를 참조해 주세요.

을 합니다.window.onbeforeunload를 참조할 수 만, 에서는 「」를 가 있습니다.returnValue'CHANGE: 'CHANGE: 'CHANGE: 'CHANGE: 'CHANGE:

var confirmOnPageExit = function (e) 
{
    // If we haven't been passed the event get the window.event
    e = e || window.event;

    var message = 'Any text will block the navigation and display a prompt';

    // For IE6-8 and Firefox prior to version 4
    if (e) 
    {
        e.returnValue = message;
    }

    // For Chrome, Safari, IE8+ and Opera 12+
    return message;
};

confirmOnPageExit사용자가 메시지 없이 계속 진행하도록 하려면 확인을 수행하고 null을 반환합니다.이벤트를 확실하게 켜고 끄려면 이벤트를 제거해야 합니다.

// Turn it on - assign the function that returns the string
window.onbeforeunload = confirmOnPageExit;

// Turn it off - remove the function entirely
window.onbeforeunload = null;

원래 답변(2009년 작업)

켜려면:

window.onbeforeunload = "Are you sure you want to leave?";

끄려면:

window.onbeforeunload = null;

이것은 일반적인 사건이 아닙니다.표준적인 방법으로 구속할 수 없습니다.

값을 확인하려면?검증 프레임워크에 따라 다릅니다.

jQuery에서는 다음과 같은 경우가 있습니다(매우 기본적인 예).

$('input').change(function() {
    if( $(this).val() != "" )
        window.onbeforeunload = "Are you sure you want to leave?";
});

onbeforeunloadMicrosoft-ism은 표준 솔루션에 가장 가깝지만 브라우저의 지원은 일정하지 않습니다.예를 들어 Opera의 경우 버전 12 이후에서만 작동합니다(이 문서에서는 베타판입니다).

또한 Mozilla Developer Network에서 설명한 바와 같이 최대 호환성을 위해서는 단순히 문자열을 반환하는 것 이상의 작업을 수행해야 합니다.

예:네비게이션 프롬프트를 활성화/비활성화하기 위한 다음 두 가지 기능을 정의합니다(MDN 예 참조).

function enableBeforeUnload() {
    window.onbeforeunload = function (e) {
        return "Discard changes?";
    };
}
function disableBeforeUnload() {
    window.onbeforeunload = null;
}

다음으로 다음과 같은 폼을 정의합니다.

<form method="POST" action="" onsubmit="disableBeforeUnload();">
    <textarea name="text"
              onchange="enableBeforeUnload();"
              onkeyup="enableBeforeUnload();">
    </textarea>
    <button type="submit">Save</button>
</form>

이렇게 하면 텍스트 영역을 변경한 경우에만 이동에 대한 경고가 표시되고 실제로 양식을 제출할 때 메시지가 표시되지 않습니다.

이것을 크롬과 사파리에서 작동시키려면, 당신은 이것을 이렇게 해야 합니다.

window.onbeforeunload = function(e) {
    return "Sure you want to leave?";
};

참고 자료: https://developer.mozilla.org/en/DOM/window.onbeforeunload

JQuery를 사용하면 이 작업을 매우 쉽게 수행할 수 있습니다.세트로 묶을 수 있으니까.

언로드 전 실행에는 충분하지 않습니다.누군가가 편집을 시작한 경우에만 네비게이트를 트리거하여 실행하려고 합니다.

jquery 'before unload'는 나에게 효과가 있었다.

$(window).bind('beforeunload', function(){
    if( $('input').val() !== '' ){
        return "It looks like you have input you haven't submitted."
    }
});

심플한 솔루션을 찾고 있는 신규 유저에게는, Areyousure.js 를 사용해 주세요.

이렇게 하면 양식에 데이터가 입력된 경우 메시지를 표시하고 양식을 제출한 경우 메시지를 표시하지 않을 수 있습니다.

$(function () {
    $("input, textarea, select").on("input change", function() {
        window.onbeforeunload = window.onbeforeunload || function (e) {
            return "You have unsaved changes.  Do you want to leave this page and lose your changes?";
        };
    });
    $("form").on("submit", function() {
        window.onbeforeunload = null;
    });
})

Keith의 놀라운 답변에 대해 자세히 설명하겠습니다.

커스텀 경고 메시지

커스텀 경고 메시지를 허용하려면 다음과 같은 기능으로 메시지를 래핑할 수 있습니다.

function preventNavigation(message) {
    var confirmOnPageExit = function (e) {
        // If we haven't been passed the event get the window.event
        e = e || window.event;

        // For IE6-8 and Firefox prior to version 4
        if (e)
        {
            e.returnValue = message;
        }

        // For Chrome, Safari, IE8+ and Opera 12+
        return message;
    };
    window.onbeforeunload = confirmOnPageExit;
}

그런 다음 커스텀메시지로 해당 함수를 호출합니다.

preventNavigation("Baby, please don't go!!!");

네비게이션 재활성화

유효하게 , 「이네이블화」를 만 하면 .window.onbeforeunload로로 합니다.null어디서든 호출할 수 있는 깔끔하고 작은 기능으로 포장되어 있습니다.

function enableNavigation() {
    window.onbeforeunload = null;
}

jQuery를 사용하여 폼 요소에 바인딩

jQuery를 사용하면 다음과 같은 양식의 모든 요소에 쉽게 바인딩할 수 있습니다.

$("#yourForm :input").change(function() {
    preventNavigation("You have not saved the form. Any \
        changes will be lost if you leave this page.");
});

다음으로 폼을 송신할 수 있도록 합니다.

$("#yourForm").on("submit", function(event) {
    enableNavigation();
});

동적으로 수정된 양식:

preventNavigation() ★★★★★★★★★★★★★★★★★」enableNavigation()는 폼을 동적으로 변경하거나 AJAX 요청을 보내는 버튼을 클릭하는 등 필요에 따라 다른 기능에 바인딩할 수 있습니다.폼에 숨겨진 입력 요소를 추가하여 이 작업을 수행했습니다.

<input id="dummy_input" type="hidden" />

후, 하는 것을 는, 그 해, 「 」, 「 」, 「 」, 「 」, 「 」, 「 」, 「 」를 합니다.preventNavigation() 실행되다.

function somethingThatModifiesAFormDynamically() {

    // Do something that modifies a form

    // ...
    $("#dummy_input").trigger("change");
    // ...
}

사용자가 폼을 변경하기 시작하면 부울 플래그가 설정됩니다.사용자가 페이지에서 벗어나려고 하면 window.onload 이벤트에서 플래그를 확인합니다.플래그가 설정되어 있는 경우 메시지를 문자열로 반환하여 표시합니다.메시지를 문자열로 반환하면 메시지가 포함된 확인 대화 상자가 나타납니다.

Ajax를 사용하여 변경을 커밋하는 경우 플래그를 다음과 같이 설정할 수 있습니다.false변경이 커밋된 후(즉, Ajax 성공 이벤트)

이거 한번 써봐 100% 작동해

<html>
<body>
<script>
var warning = true;
window.onbeforeunload = function() {  
  if (warning) {  
    return "You have made changes on this page that you have not yet confirmed. If you navigate away from this page you will lose your unsaved changes";  
    }  
}

$('form').submit(function() {
   window.onbeforeunload = null;
});
</script>
</body>
</html>

표준에서는 언로드 전 이벤트를 취소하거나 반환값을 null이 아닌 값으로 설정하여 프롬프트를 제어할 수 있다고 명시되어 있습니다.또한 작성자는 returnValue 대신 Event.proventDefault()를 사용해야 하며 사용자에게 표시되는 메시지는 커스터마이즈할없습니다.

69.0.3497.92 현재 크롬은 표준을 충족하지 못하고 있습니다., 버그 보고가 접수되어 리뷰가 진행 중입니다.Chrome에서는 핸들러가 반환하는 값이 아니라 이벤트 개체를 참조하여 returnValue를 설정해야 합니다.

변경 여부를 추적하는 것은 작성자의 책임입니다.변수를 사용하거나 이벤트가 필요한 경우에만 처리되도록 함으로써 변경할 수 있습니다.

window.addEventListener('beforeunload', function (e) {
    // Cancel the event as stated by the standard.
    e.preventDefault();
    // Chrome requires returnValue to be set.
    e.returnValue = '';
});
    
window.location = 'about:blank';

추가할 수 있습니다.onchangeJS에서 변수를 설정하는 텍스트 영역(또는 다른 필드)의 이벤트.사용자가 페이지를 닫으려고 하면(window.onload) 변수 값을 확인하고 그에 따라 경보를 표시합니다.

이 스레드에 대한 모든 답을 바탕으로 다음 코드를 작성했고, 나에게 효과가 있었습니다.

온로드 이벤트를 체크해야 하는 일부 입력/텍스트 영역 태그만 있는 경우 HTML5 데이터 속성을 다음과 같이 할당할 수 있습니다.data-onunload="true"

예를 들어,

<input type="text" data-onunload="true" />
<textarea data-onunload="true"></textarea>

Javascript(jQuery)는 다음과 같습니다.

$(document).ready(function(){
    window.onbeforeunload = function(e) {
        var returnFlag = false;
        $('textarea, input').each(function(){
            if($(this).attr('data-onunload') == 'true' && $(this).val() != '')
                returnFlag = true;
        });

        if(returnFlag)
            return "Sure you want to leave?";   
    };
});

여기 내 html이 있다.

<!DOCTYPE HMTL>
<meta charset="UTF-8">
<html>
<head>
<title>Home</title>
<script type="text/javascript" src="script.js"></script>
</head>

 <body onload="myFunction()">
    <h1 id="belong">
        Welcome To My Home
    </h1>
    <p>
        <a id="replaceME" onclick="myFunction2(event)" href="https://www.ccis.edu">I am a student at Columbia College of Missouri.</a>
    </p>
</body>

그래서 자바스크립트에서도 비슷한 작업을 했습니다.

var myGlobalNameHolder ="";

function myFunction(){
var myString = prompt("Enter a name", "Name Goes Here");
    myGlobalNameHolder = myString;
    if (myString != null) {
        document.getElementById("replaceME").innerHTML =
        "Hello " + myString + ". Welcome to my site";

        document.getElementById("belong").innerHTML =
        "A place you belong";
    }   
}

// create a function to pass our event too
function myFunction2(event) {   
// variable to make our event short and sweet
var x=window.onbeforeunload;
// logic to make the confirm and alert boxes
if (confirm("Are you sure you want to leave my page?") == true) {
    x = alert("Thank you " + myGlobalNameHolder + " for visiting!");
}
}

TextAreaonChange 이벤트에 ChangeFlag를 true로 설정하면 쉽게 할 수 있습니다.javascript를 사용하여 ChangeFlag 값을 기반으로 확인 대화 상자를 표시합니다.confirm이 true를 반환하면 폼을 파기하고 요청된 페이지로 이동하고 그렇지 않으면 do-nothing으로 이동합니다.

사용하고 싶은 것은 JavaScript의 onunload 이벤트입니다.

다음은 예를 제시하겠습니다.http://www.w3schools.com/jsref/event_onunload.asp

WebAPI -> Window Event Handler -> on unload from 、window.addEventListener()및 그beforeunload이벤트 대신onbeforeunload.

구문 예시

window.addEventListener("beforeunload", function(event) { ... });
window.onbeforeunload = function(event) { ... };

주의: HTML 사양에는 작성자가 다음 명령을 사용해야 한다고 명시되어 있습니다.Event.preventDefault()사용하는 대신 방법Event.returnValue사용자에게 프롬프트를 표시합니다.

따라서 사용자의 경우 코드는 다음과 같습니다.

//javascript
window..addEventListener("beforeunload", function(event) { 
    //your code

    // If you prevent default behaviour in Mozilla Firefox prompt will always be shown
    e.preventDefault();

    // Chrome requires returnValue to be set
    e.returnValue = '';
})

body tag에는 javascript 함수를 호출할 수 있는 "onunload" 파라미터가 있습니다.false를 반환하면 네비게이트가 회피되지 않습니다.

언급URL : https://stackoverflow.com/questions/1119289/how-to-show-the-are-you-sure-you-want-to-navigate-away-from-this-page-when-ch

반응형