Programming

자바 스크립트를 사용하여 브라우저 뒤로 버튼을 중지하는 방법

procodes 2020. 7. 1. 22:23
반응형

자바 스크립트를 사용하여 브라우저 뒤로 버튼을 중지하는 방법


PHP에서 온라인 퀴즈 앱을 만들고 있습니다. 사용자가 시험으로 돌아 가지 못하도록 제한하고 싶습니다. 다음 스크립트를 시도했지만 타이머가 중지됩니다. 어떻게해야합니까?

소스 코드를 포함 시켰습니다. 타이머는 cdtimer.js에 저장됩니다

<script type="text/javascript">
        window.history.forward();
        function noBack()
        {
            window.history.forward();
        }
</script>
<body onLoad="noBack();" onpageshow="if (event.persisted) noBack();" onUnload="">

mysql에서 시험 기간이 걸리는 시험 타이머가 있습니다. 타이머는 그에 따라 시작되지만 뒤로 버튼을 비활성화하기 위해 코드를 넣으면 중지됩니다. 내 문제는 무엇입니까?


뒤로 버튼을 비활성화하면 실제로 작동하지 않는 데는 여러 가지 이유가 있습니다. 가장 좋은 방법은 사용자에게 경고하는 것입니다.

window.onbeforeunload = function() { return "Your work will be lost."; };

이 페이지에는 뒤로 버튼을 비활성화 있는 여러 가지 방법이 나열되어 있지만 보장되는 것은 없습니다.

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


일반적으로 웹 브라우저의 기본 동작을 재정의하는 것은 좋지 않습니다. 클라이언트 측 스크립트에는 보안상의 이유로이를 수행 할 수있는 충분한 권한이 없습니다.

비슷한 질문이 거의 없습니다.

당신은 할 수-하지 실제로 해제 브라우저의 뒤로 버튼을 누릅니다. 그러나 논리를 사용하여 마술을 사용하면 사용자가 다시 탐색하지 못하게되어 마치 비활성화 된 것처럼 인상을 줄 수 있습니다. 다음은 스 니펫을 확인하는 방법입니다.

(function (global) { 

    if(typeof (global) === "undefined") {
        throw new Error("window is undefined");
    }

    var _hash = "!";
    var noBackPlease = function () {
        global.location.href += "#";

        // making sure we have the fruit available for juice (^__^)
        global.setTimeout(function () {
            global.location.href += "!";
        }, 50);
    };

    global.onhashchange = function () {
        if (global.location.hash !== _hash) {
            global.location.hash = _hash;
        }
    };

    global.onload = function () {            
        noBackPlease();

        // disables backspace on page except on input fields and textarea..
        document.body.onkeydown = function (e) {
            var elm = e.target.nodeName.toLowerCase();
            if (e.which === 8 && (elm !== 'input' && elm  !== 'textarea')) {
                e.preventDefault();
            }
            // stopping event bubbling up the DOM tree..
            e.stopPropagation();
        };          
    }

})(window);

이것은 순수한 JavaScript로되어 있으므로 대부분의 브라우저에서 작동합니다. 또한 백 스페이스 키를 비활성화 하지만 키는 input필드 내에서 정상적으로 작동합니다 textarea.

권장 설정 :

이 스 니펫을 별도의 스크립트에 넣고이 동작을 원하는 페이지에 포함 시키십시오. 현재 설정에서는 onload이 코드의 이상적인 진입 점 인 DOM 이벤트를 실행 합니다.

데모 데모!

다음 브라우저에서 테스트 및 검증

  • 크롬.
  • Firefox.
  • IE (8-11) 및 Edge.
  • 원정 여행.

<script>
window.location.hash="no-back-button";
window.location.hash="Again-No-back-button";//again because google chrome don't insert first hash into history
window.onhashchange=function(){window.location.hash="no-back-button";}
</script> 

나는 이것을 발견했고, 모바일 사파리 (포스팅시 iOS9)를 포함하여 다양한 브라우저에서 정확하고 훌륭하게 작동하는 솔루션이 필요했다 . 해결책 중 어느 것도 옳지 않았습니다. 다음을 제공합니다 (IE11, FireFox, Chrome 및 Safari에서 테스트).

history.pushState(null, document.title, location.href);
window.addEventListener('popstate', function (event)
{
  history.pushState(null, document.title, location.href);
});

다음 사항에 유의하십시오.

  • history.forward()(나의 오래된 해결책)은 Mobile Safari에서 작동하지 않습니다 .- 아무것도하지 않는 것 같습니다 (즉, 사용자는 여전히 돌아갈 수 있습니다). history.pushState()그들 모두에 대해 작동합니다.
  • 에 대한 세 번째 인수 history.pushState()url 입니다. 페이지에서 새로 고침 / 재로드를 시도 할 때까지 문자열을 전달 'no-back-button'하거나 'pagename'확인하는 것처럼 보이는 솔루션 은 브라우저가 해당 페이지를 URL로 찾으려고하면 "페이지를 찾을 수 없음"오류가 발생합니다. (브라우저는 때 추한 페이지에 주소 표시 줄에 해당 문자열을 포함 할 가능성이있다.) location.hrefURL을 사용해야합니다.
  • 두 번째 인수 history.pushState()제목 입니다. 웹을 둘러 보면 대부분의 장소에서 "사용되지 않음"이라고 말하며 여기에있는 모든 솔루션이이를 통과 null합니다. 그러나 적어도 모바일 사파리에서는 페이지의 URL을 사용자가 액세스 할 수있는 기록 드롭 다운에 넣습니다. 그러나 일반적으로 페이지 방문에 대한 항목을 추가하면 title을 넣는 것이 좋습니다. 따라서 document.title그것을 통과 하면 동일한 행동이 발생합니다.

이 코드는 HTML5 History API를 지원하는 최신 브라우저에서 뒤로 버튼을 비활성화합니다. 정상적인 상황에서 뒤로 단추를 누르면 한 단계 뒤로 이동하여 이전 페이지로 돌아갑니다. history.pushState ()를 사용하면 현재 페이지에 추가 하위 단계를 추가하기 시작합니다. 작동 방식은 history.pushState ()를 세 번 사용한 다음 뒤로 버튼을 누르기 시작하면 처음 세 번은 이러한 하위 단계에서 다시 탐색 한 다음 네 번째로 돌아가는 것입니다. 이전 페이지.

이 동작을 이벤트의 이벤트 리스너와 결합하면 popstate기본적으로 무한한 하위 상태 루프를 설정할 수 있습니다. 따라서 페이지를로드하고 하위 상태를 누른 다음 뒤로 버튼을 누르면 하위 상태가 팝업되고 다른 상태도 푸시되므로 뒤로 버튼을 다시 누르면 하위 상태가 없어지지 않습니다. . 뒤로 버튼을 비활성화해야한다고 생각되면 여기로 이동합니다.

history.pushState(null, null, 'no-back-button');
window.addEventListener('popstate', function(event) {
  history.pushState(null, null, 'no-back-button');
});

이것이 내가 그것을 달성 할 수있는 방법입니다. Chrome 및 Safari에서 위치를 제대로 변경하지 못했습니다. location.hash는 크롬 및 사파리의 기록에 항목을 생성하지 않습니다. 따라서 pushstate를 사용해야합니다. 이것은 모든 브라우저에서 저에게 효과적입니다.

    history.pushState({ page: 1 }, "title 1", "#nbb");
    window.onhashchange = function (event) {
        window.location.hash = "nbb";

    };

<html>
<head>
    <title>Disable Back Button in Browser - Online Demo</title>
    <style type="text/css">
        body, input {
            font-family: Calibri, Arial;
        }
    </style>
    <script type="text/javascript">
        window.history.forward();
        function noBack() {
            window.history.forward();
        }
    </script>
</head>
<body onload="noBack();" onpageshow="if (event.persisted) noBack();" onunload="">
    <H2>Demo</H2>
    <p>This page contains the code to avoid Back button.</p>
    <p>Click here to Goto <a href="noback.html">NoBack Page</a></p>
</body>
</html>

    history.pushState(null, null, location.href);
    window.onpopstate = function () {
        history.go(1);
    };


jordanhollinger.com에 관한이 기사 는 내가 느끼는 최고의 옵션입니다. 면도기의 대답과 비슷하지만 조금 더 명확합니다. 아래 코드; Jordan Hollinger에 대한 전체 크레딧 :

이전 페이지 :

<a href="/page-of-no-return.htm#no-back>You can't go back from the next page</a>

반환되지 않은 JavaScript 페이지 :

// It works without the History API, but will clutter up the history
var history_api = typeof history.pushState !== 'undefined'

// The previous page asks that it not be returned to
if ( location.hash == '#no-back' ) {
  // Push "#no-back" onto the history, making it the most recent "page"
  if ( history_api ) history.pushState(null, '', '#stay')
  else location.hash = '#stay'

  // When the back button is pressed, it will harmlessly change the url
  // hash from "#stay" to "#no-back", which triggers this function
  window.onhashchange = function() {
    // User tried to go back; warn user, rinse and repeat
    if ( location.hash == '#no-back' ) {
      alert("You shall not pass!")
      if ( history_api ) history.pushState(null, '', '#stay')
      else location.hash = '#stay'
    }
  }
}

history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
    history.pushState(null, null, document.URL);
});

이 자바 스크립트는 사용자가 되돌아 갈 수 없도록합니다 (Chrome, FF, IE, Edge에서 작동)


브라우저 백 이벤트 제한

window.history.pushState(null, "", window.location.href);
window.onpopstate = function () {
    window.history.pushState(null, "", window.location.href);
};

쉽게 사용해보십시오 :

history.pushState(null, null, document.title);
window.addEventListener('popstate', function () {
    history.pushState(null, null, document.title);
});

나중에 페이지를 방해하지 않고 뒤로 화살표를 끊는 매우 간단하고 깨끗한 기능입니다.

혜택:

  • 즉시로드하고 원래 해시를 복원하므로 사용자가 URL을 눈에 띄게 변경하여주의를 분산시키지 않습니다.
  • 사용자는 여전히 10 번 뒤로 밀면 종료 할 수 있지만 실수는 아닙니다.
  • 사용하는 다른 솔루션과 같은 사용자 간섭 없음 onbeforeunload
  • 한 번만 실행되며 상태를 추적하는 데 사용하는 경우 추가 해시 조작을 방해하지 않습니다.
  • 거의 보이지 않는 원본 해시를 복원합니다.
  • setInterval느린 브라우저를 중단하지 않고 항상 작동하도록 사용 합니다.
  • 순수한 Javascript는 HTML5 히스토리가 필요하지 않으며 어디에서나 작동합니다.
  • 눈에 거슬리지 않고 단순하며 다른 코드와 잘 어울립니다.
  • unbeforeunload모달 대화 상자에서 사용자를 방해하는 것을 사용하지 않습니다 .
  • 소란없이 작동합니다.

참고 : 다른 솔루션 중 일부는을 사용 onbeforeunload합니다. 제발 하지 않는 사용 onbeforeunload등의 조동사와 같은 사용자가 창을 닫으려고 할 때마다 대화 상자가 팝업이 목적, 히트 backarrow을 위해 onbeforeunload실제로 화면 천국에 변경 한 경우 '와 같은 보통 드문 경우에 적합 이 목적을 위해서가 아니라 그들을 구했습니다.

작동 원리

  1. 페이지로드시 실행
  2. 원래 해시를 저장합니다 (URL에있는 경우).
  3. # / noop / {1..10}을 해시에 순차적으로 추가
  4. 원래 해시를 복원

그게 다야. 더 이상 혼란스럽지 않고 백그라운드 이벤트 모니터링도 없으며 다른 것도 없습니다.

1 초에 사용

배포하려면 페이지 또는 JS의 아무 곳에 나 추가하십시오.

<script>
/* break back button */                                                                        
window.onload=function(){                                                                      
  var i=0; var previous_hash = window.location.hash;                                           
  var x = setInterval(function(){                                                              
    i++; window.location.hash = "/noop/" + i;                                                  
    if (i==10){clearInterval(x);                                                               
      window.location.hash = previous_hash;}                                                   
  },10);
}
</script>

이것은 브라우저에서 뒤로 버튼과 비활성화하는 백 스페이스 버튼을 비활성화하는 데 도움이 된 것으로 보입니다.

history.pushState(null, null, $(location).attr('href'));
    window.addEventListener('popstate', function () {
        history.pushState(null, null, $(location).attr('href'));
    });

   <script src="~/main.js" type="text/javascript"></script>
    <script type="text/javascript">
        window.history.forward();
        function noBack() { window.history.forward(); } </script>

당신은 단순히 이것을 할 수없고해서는 안됩니다. 그러나 이것은 도움이 될 수 있습니다

<script type = "text/javascript" >
history.pushState(null, null, 'pagename');
window.addEventListener('popstate', function(event) {
history.pushState(null, null, 'pagename');
});
</script>

크롬 및 파이어 폭스에서 작동


IE에서 백 스페이스 버튼이 기본적으로 "뒤로"로 작동하지 않도록하려면 다음을 시도하십시오.

<script language="JavaScript">
$(document).ready(function() {
$(document).unbind('keydown').bind('keydown', function (event) {
    var doPrevent = false;


    if (event.keyCode === 8 ) {
        var d = event.srcElement || event.target;
        if ((d.tagName.toUpperCase() === 'INPUT' && 
             (
                 d.type.toUpperCase() === 'TEXT' ||
                 d.type.toUpperCase() === 'PASSWORD' || 
                 d.type.toUpperCase() === 'FILE' || 
                 d.type.toUpperCase() === 'EMAIL' || 
                 d.type.toUpperCase() === 'SEARCH' || 
                 d.type.toUpperCase() === 'DATE' )
             ) || 
             d.tagName.toUpperCase() === 'TEXTAREA') {
            doPrevent = d.readOnly || d.disabled;
        }
        else {

            doPrevent = true;
        }
    }

    if (doPrevent) {
        event.preventDefault();
    }

    try {
        document.addEventListener('keydown', function (e) {
               if ((e.keyCode === 13)){
                  // alert('Enter keydown');
                   e.stopPropagation();
                   e.preventDefault();
               }



           }, true);
        } catch (err) {}
    });
});
</script>

나는 완벽한 아직 솔루션이 실제로 매우 간단하다고 생각합니다.

기본적으로 진행중인 문서 'mouseenter'/ 'mouseleave'이벤트와 함께 창의 "onbeforeunload"이벤트를 할당하므로 클릭이 문서 범위를 벗어난 경우에만 경고가 트리거됩니다 (브라우저의 뒤로 또는 앞으로 버튼 일 수 있음).

$(document).on('mouseenter', function(e) { 
        window.onbeforeunload = null; 
    }
);

$(document).on('mouseleave', function(e) { 
        window.onbeforeunload = function() { return "You work will be lost."; };
    }
);

최신 브라우저에서는 다음과 같이 작동합니다.

// https://developer.mozilla.org/en-US/docs/Web/API/History_API
let popHandler = () => {
  if (confirm('Go back?')) {
    window.history.back() 
  } else {
    window.history.forward()
    setTimeout(() => {
      window.addEventListener('popstate', popHandler, {once: true})
    }, 50) // delay needed since the above is an async operation for some reason
  }
}
window.addEventListener('popstate', popHandler, {once: true})
window.history.pushState(null,null,null)

하나의 HTML 페이지 (index.html)를 만듭니다. 또한 (script) 폴더 / 디렉토리 안에 하나 (mechanism.js)를 만듭니다. 그런 다음 필요에 따라 form, table, span 및 div 태그를 사용하여 모든 컨텐츠를 (index.html) 안에 배치합니다. 자, 여기 뒤로 / 앞으로 아무것도하지 않는 속임수가 있습니다!

첫째, 페이지가 하나만 있다는 사실! 둘째, 일반 링크를 통해 필요할 때 span / div 태그와 함께 JavaScript를 사용하여 동일한 페이지에서 컨텐츠를 숨기고 표시합니다!

'index.html'내부 :

    <td width="89px" align="right" valign="top" style="letter-spacing:1px;">
     <small>
      <b>
       <a href="#" class="traff" onClick="DisplayInTrafficTable();">IN</a>&nbsp;
      </b>
     </small>
     [&nbsp;<span id="inCountSPN">0</span>&nbsp;]
    </td>

내부 'mechanism.js':

    function DisplayInTrafficTable()
    {
     var itmsCNT = 0;
     var dsplyIn = "";
     for ( i=0; i<inTraffic.length; i++ )
     {
      dsplyIn += "<tr><td width='11'></td><td align='right'>" + (++itmsCNT) + "</td><td width='11'></td><td><b>" + inTraffic[i] + "</b></td><td width='11'></td><td>" + entryTimeArray[i] + "</td><td width='11'></td><td>" + entryDateArray[i] + "</td><td width='11'></td></tr>";
     }
     document.getElementById('inOutSPN').innerHTML = "" +
                                             "<table border='0' style='background:#fff;'><tr><th colspan='21' style='background:#feb;padding:11px;'><h3 style='margin-bottom:-1px;'>INCOMING TRAFFIC REPORT</h3>" + DateStamp() + "&nbsp;&nbsp;-&nbsp;&nbsp;<small><a href='#' style='letter-spacing:1px;' onclick='OpenPrintableIn();'>PRINT</a></small></th></tr><tr style='background:#eee;'><td></td><td><b>###</b></td><td></td><td><b>ID #</b></td><td></td><td width='79'><b>TYPE</b></td><td></td><td><b>FIRST</b></td><td></td><td><b>LAST</b></td><td></td><td><b>PLATE #</b></td><td></td><td><b>COMPANY</b></td><td></td><td><b>TIME</b></td><td></td><td><b>DATE</b></td><td></td><td><b>IN / OUT</b></td><td></td></tr>" + dsplyIn.toUpperCase() + "</table>" +
                                             "";
     return document.getElementById('inOutSPN').innerHTML;
    }

It looks hairy, but note the function names and calls, embedded HTML, and the span tag id calls. This was to show how you can inject different HTML into same span tag on same page! How can Back/Forward affect this design? It cannot, because you are hiding objects and replacing others all on the same page!

How to hide and display? Here goes: Inside functions in ' mechanism.js ' as needed, use:

    document.getElementById('textOverPic').style.display = "none"; //hide
    document.getElementById('textOverPic').style.display = "";     //display

Inside ' index.html ' call functions through links:

    <img src="images/someimage.jpg" alt="" />
    <span class="textOverPic" id="textOverPic"></span>

and

    <a href="#" style="color:#119;font-size:11px;text-decoration:none;letter-spacing:1px;" onclick="HiddenTextsManager(1);">Introduction</a>

I hope I did not give you a headache. Sorry if I did :-)


In my case this was a shopping order. So what I did was disable the button. When the user clicked back, the button was disabled still. When they clicked back one more time, and then clicked a page button to go forward. I knew their order was submitted and skipped to another page.

In the case when the page actually refreshed which would make the button (theoretically), available; I was then able to react in the page load that the order is already submitted and redirect then too.


<script language="JavaScript">
    javascript:window.history.forward(1);
</script>

//"use strict";
function stopBackSpace(e) {
    var ev = e || window.event;
    var obj = ev.target || ev.srcElement;
    var t = obj.type || obj.getAttribute('type');

    var vReadOnly = obj.getAttribute('readonly');
    var vEnabled = obj.getAttribute('enabled');
    // null
    vReadOnly = (vReadOnly == null) ? false : vReadOnly;
    vEnabled = (vEnabled == null) ? true : vEnabled;
    // when click Backspace,judge the type of obj.

    var flag1 = ((t == 'password' || t == 'text' || t == 'textarea') && ((vReadOnly == true || vReadOnly == 'readonly') || vEnabled != true)) ? true : false;

    var flag2 = (t != 'password' && t != 'text' && t != 'textarea') ? true : false;

    if (flag2) {
        e.keyCode = 0;
        e.cancelBubble = true;
        return false;
    }
    if (flag1) {
        e.keyCode = 0;
        e.cancelBubble = true;
        return false;
    }
}
if (typeof($) == 'function') {
    $(function() {
        $(document).keydown(function(e) {
            if (e.keyCode == 8) {
                return stopBackSpace(e);
            }
        });
    });
} else {
    document.onkeydown = stopBackSpace;
}

참고URL : https://stackoverflow.com/questions/12381563/how-to-stop-browser-back-button-using-javascript

반응형