Programing

브라우저의 뒤로 버튼 비활성화

lottogame 2020. 8. 23. 09:36
반응형

브라우저의 뒤로 버튼 비활성화


브라우저의 뒤로 버튼을 비활성화하는 방법 (브라우저 간)?


이 질문은 이것과 매우 유사 하나 ...

이 작업을 수행하려면 캐시를 강제로 만료시켜야합니다. 페이지 코드 뒤에 다음 코드를 배치하십시오.

Page.Response.Cache.SetCacheability(HttpCacheability.NoCache)

예상되는 브라우저 동작을 비활성화하지 마십시오.

페이지가 사용자가 한두 페이지 뒤로 이동할 가능성을 처리하도록합니다. 그들의 소프트웨어를 불구로 만들려고하지 마십시오.


JavaScript를 사용하여 뒤로 버튼을 비활성화하는 약간의 해킹을 생각해 냈습니다. Chrome 10, firefox 3.6 및 IE9에서 확인했습니다.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<title>Untitled Page</title>
<script type = "text/javascript" >
function changeHashOnLoad() {
     window.location.href += "#";
     setTimeout("changeHashAgain()", "50"); 
}

function changeHashAgain() {
  window.location.href += "1";
}

var storedHash = window.location.hash;
window.setInterval(function () {
    if (window.location.hash != storedHash) {
         window.location.hash = storedHash;
    }
}, 50);


</script>
</head>
<body onload="changeHashOnLoad(); ">
Try to hit the back button!
</body>
</html>

무엇을하고 있습니까?

댓글에서 :

이 스크립트는 브라우저가 검색 기록의 일부로 URL의 "#"기호 뒤에 오는 모든 것을 고려한다는 사실을 활용합니다. 이것이하는 일은 페이지가로드 될 때 "# 1"이 URL에 추가됩니다. 50ms 후에 "1"이 제거됩니다. 사용자가 "뒤로"를 클릭하면 브라우저는 URL을 "1"이 제거되기 전의 URL로 변경하지만 동일한 웹 페이지이므로 브라우저가 페이지를 다시로드 할 필요가 없습니다. – 요시 샤쇼


다른 사람들은 "이렇게하지 마십시오"라고 말하는 접근 방식을 취했지만 실제로 포스터의 질문에 답하지 않습니다. 모두가 이것이 나쁜 생각이라는 것을 알고 있다고 가정 해 봅시다. 그러나 어쨌든 그것이 어떻게 이루어 졌는지 궁금합니다 ...

사용자 브라우저에서 뒤로 버튼을 비활성화 할 수는 없지만 사용자가 돌아갈 경우 응용 프로그램이 중단되도록 (오류 메시지를 표시하고 사용자가 다시 시작해야 함) 만들 수 있습니다.

이를 위해 내가 본 한 가지 접근 방식은 애플리케이션 내의 모든 URL과 모든 양식에 토큰을 전달하는 것입니다. 토큰은 모든 페이지에서 다시 생성되며 사용자가 새 페이지를로드하면 이전 페이지의 모든 토큰이 무효화됩니다.

사용자가 페이지를로드 할 때 페이지는 올바른 토큰 (이전 페이지의 모든 링크 / 양식에 제공된)이 전달 된 경우에만 표시됩니다.

제 은행에서 제공하는 온라인 뱅킹 애플리케이션은 다음과 같습니다. 뒤로 버튼을 전혀 사용하면 더 이상 링크가 작동하지 않고 더 이상 페이지를 다시로드 할 수 없습니다. 대신 뒤로 갈 수 없으며 다시 시작해야한다는 알림이 표시됩니다.


내가 직접 답을 찾고있는 동안 "Best Practice"는 .... 구식입니다 ... 브라우저처럼. (정말 브라우저는 추악한 화석입니다)

가장 안전한 방법은 브라우저가 사용자가 페이지에 인터페이스를 제어 할 수있는 기능을 부여 할 수있는 메서드 / 요청을 구현하는 것입니다.

왜? 내 현재 프로젝트의 경우 100 % JavaScript로 구축되고 제어되는 인터페이스를 구축하고 있기 때문입니다. 페이지 변경이 없기 때문에 뒤로 버튼은 내 프로젝트에 없습니다. (즉, 새로 고침 때문에 피투성이 빠르고 페이지 깜박임이 없습니다. 실제 응용 프로그램과 같습니다!)

인터페이스를 "하이 잭"하는 기능이없는 이유를 알고 있으며 이해합니다. 하지만 최소한 브라우저에서 요청할 수 있어야합니다! 이제 그것은 하이 잭 위험이없는 진정한 "모범 사례"가 될 것입니다.

그러나 브라우저는 브라우저입니다. 나는 이와 관련하여 어떤 일이 일어날 것이라고 기대하지 않습니다.


나는 같은 질문을 찾고 있었고 사이트에서 다음 코드를 발견했습니다. 여기에서 공유 할 생각 :

function noBack()
{
   window.history.forward()
}
noBack();
window.onload = noBack;
window.onpageshow = function(evt){ if(evt.persisted) noBack(); }
window.onunload = function(){ void(0); }

그러나 위의 사용자들이 언급했듯이 이것은 결코 좋은 습관이 아니며 모든 이유로 피해야합니다.


클라이언트 측 기술에 의존하면 우회 할 수 있습니다. 예를 들어 자바 스크립트가 비활성화 될 수 있습니다. 또는 사용자가 JS 스크립트를 실행하여 제한 사항을 해결할 수 있습니다.

내 생각 엔 사용자 세션을 서버 측에서 추적하고 사용자 / 브라우저를 필요한 페이지로 리디렉션 (Response.Redirect가 아닌 Server.Transfer에서와 같이) 하여이 작업을 수행 할 수 있습니다.


<body onLoad="if(history.length>0)history.go(+1)">

몇 가지 다른 구현이 있습니다. IE 용 플래시 솔루션과 일부 iframe / 프레임 솔루션이 있습니다. 이것을 확인하십시오

http://www.contentwithstyle.co.uk/content/fixing-the-back-button-and-enabling-bookmarking-for-ajax-apps

BTW: There are plenty of valid reasons to disable (or at least prevent 1 step) a back button -- look at gmail as an example which implements the hash solution discussed in the above article.

Google "how ajax broke the back button" and you'll find plenty of articles on user testing and the validity of disabling the back button.


I also had the same problem, use this Java script function on head tag or in , its 100% working fine, would not let you go back.

 <script type = "text/javascript" >
      function preventBack(){window.history.forward();}
        setTimeout("preventBack()", 0);
        window.onunload=function(){null};
    </script>

Try this code. Worked for me. It basically changes the hash as soon as the page loads which changes recent history page by adding "1" on URL. So when you hit back button, it redirects to same page everytime.

 <script type="text/javascript">
    var storedHash = window.location.hash;
    function changeHashOnLoad() { window.location.hash = "1";}
    window.onhashchange = function () {
        window.location.hash = storedHash;
    }
</script>

<body onload="changeHashOnLoad(); ">

</bod>

You should be using posts with proper expires and caching headers.


Instead of trying to disable the browser back button it's better to support it. .NET 3.5 can very well handle the browser back (and forward) buttons. Search with Google: "Scriptmanager EnableHistory". You can control which user actions will add an entry to the browser's history (ScriptManager -> AddHistoryPoint) and your ASP.NET application receives an event whenever the user clicks the browser Back/Forward buttons. This will work for all known browsers


Globally, disabling the back button is indeed bad practice. But, in certain situations, the back button functionality doesn't make sense.

Here's one way to prevent unwanted navigation between pages:

Top page (file top.php):

<?php
    session_start();
    $_SESSION[pid]++;
    echo "top page $_SESSION[pid]";
    echo "<BR><a href='secondary.php?pid=$_SESSION[pid]'>secondary page</a>";
?>

Secondary page (file secondary.php):

<?php
    session_start();
    if ($_SESSION[pid] != $_GET[pid]) 
        header("location: top.php");
    else {
        echo "secondary page $_SESSION[pid]";
        echo "<BR><a href='top.php'>top</a>";
    }
?>

The effect is to allow navigating from the top page forward to the secondary page and back (e.g. Cancel) using your own links. But, after returning to the top page the browser back button is prevented from navigating to the secondary page.


Even I faced the same situation before...and didn't have any help. try these things maybe these will work for you

in login page <head> tag:

<script type="text/javascript">
    window.history.forward();
</script>

in Logout Button I did this:

protected void Btn_Logout_Click(object sender, EventArgs e)      
{
    connObj.Close();
    Session.Abandon();
    Session.RemoveAll();
    Session.Clear();
    HttpContext.Current.Session.Abandon();
}

and on login page I have put the focus on Username textbox like this:

protected void Page_Load(object sender, EventArgs e)
{
    _txtUsername.Focus();
}

hope this helps... :) someone plz teach me how to edit this page...


IF you need to softly suppress the delete and backspace keys in your Web app, so that when they are editing / deleting items the page does not get redirected unexpectedly, you can use this code:

window.addEventListener('keydown', function(e) {
  var key = e.keyCode || e.which;
  if (key == 8 /*BACKSPACE*/ || key == 46/*DELETE*/) {
    var len=window.location.href.length;
    if(window.location.href[len-1]!='#') window.location.href += "#";
  }
},false);

Try this code. You just need to implement this code in master page and it will work for you on all the pages

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

The problem with Yossi Shasho's Code is that the page is scrolling to the top every 50 ms. So I have modified that code. Now its working fine on all modern browsers, IE8 and above

var storedHash = window.location.hash;
function changeHashOnLoad() {
    window.location.href += "#";
    setTimeout("changeHashAgain()", "50");
}

function changeHashAgain() {
    window.location.href += "1";
}

function restoreHash() {
    if (window.location.hash != storedHash) {
        window.location.hash = storedHash;
    }
}

if (window.addEventListener) {
    window.addEventListener("hashchange", function () {
        restoreHash();
    }, false);
}
else if (window.attachEvent) {
    window.attachEvent("onhashchange", function () {
        restoreHash();
    });
}
$(window).load(function () { changeHashOnLoad(); });

This seems to have worked for us.

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

<script>
    $(document).ready(function() {
        function disableBack() { window.history.forward() }

        window.onload = disableBack();
        window.onpageshow = function(evt) { if (evt.persisted) disableBack() }
    });
</script>

참고URL : https://stackoverflow.com/questions/961188/disable-browsers-back-button

반응형