Programing

사용자가 브라우저 기록으로 돌아갈 수 있는지 확인하는 방법

lottogame 2020. 7. 2. 07:48
반응형

사용자가 브라우저 기록으로 돌아갈 수 있는지 확인하는 방법


JavaScript를 사용하여 기록이 있는지 여부를 확인하고 싶습니다. 브라우저에서 뒤로 버튼을 사용할 수 있는지 여부를 의미합니다.


짧은 대답 : 할 수 없습니다.

기술적으로 정확한 방법이 있습니다.이 방법은 속성을 확인하는 것입니다.

history.previous

그러나 작동하지 않습니다. 이것의 문제는 대부분의 브라우저에서 보안 위반으로 간주되며 일반적으로 undefined를 반환한다는 것 입니다.

history.length

다른 사람들이 제안한 속성입니다 ...
그러나 길이는 역사의 현재 위치나타내지 않기 때문에 완전히 작동하지 않습니다 . 또한 항상 같은 숫자로 시작하지는 않습니다. 예를 들어 랜딩 페이지를 갖도록 설정되지 않은 브라우저는 0에서 시작하지만 랭킹 페이지를 사용하는 다른 브라우저는 1에서 시작합니다.

대체 텍스트

대부분의 경우 다음을 호출하는 링크가 추가됩니다.

history.back();

또는

 history.go(-1);

되돌아 갈 수 없다면 링크를 클릭해도 아무런 효과가 없을 것으로 예상됩니다.


확인하는 또 다른 방법이 있습니다-리퍼러를 확인하십시오. 첫 페이지에는 일반적으로 빈 리퍼러가 있습니다 ...

if (document.referrer == "") {
    window.close()
} else {
    history.back()
}

내 코드는 브라우저가 한 페이지 뒤로 돌아가도록 허용하고 실패하면 대체 URL을로드합니다. 또한 해시 태그 변경도 감지합니다.

뒤로 버튼을 사용할 수없는 경우 대체 URL은 500ms 후에로드되므로 브라우저는 이전 페이지를로드 할 시간이 충분합니다. window.history.go(-1);js 스크립트가 아직 중지되지 않았기 때문에 대체 URL을로드하면 브라우저에서 대체 URL을 사용하게됩니다.

function historyBackWFallback(fallbackUrl) {
    fallbackUrl = fallbackUrl || '/';
    var prevPage = window.location.href;

    window.history.go(-1);

    setTimeout(function(){ 
        if (window.location.href == prevPage) {
            window.location.href = fallbackUrl; 
        }
    }, 500);
}

이것은 트릭을 수행하는 것 같습니다.

function goBackOrClose() {  

    window.history.back();
    window.close(); 

    //or if you are not interested in closing the window, do something else here
    //e.g. 
    theBrowserCantGoBack();

}

history.back ()을 호출 한 다음 window.close ()를 호출하십시오. 브라우저가 히스토리로 돌아갈 수 있으면 다음 명령문으로 이동할 수 없습니다. 되돌아 갈 수 없으면 창을 닫습니다.

그러나 URL을 입력하여 페이지에 도달하면 firefox에서 스크립트가 창을 닫을 수 없습니다.


뒤로 버튼을 사용할 수 있는지 직접 확인할 수 없습니다. 를 볼 수 history.length>0있지만 현재 페이지 보다 앞쪽페이지 있는 경우에도 마찬가지입니다. 이 때 뒤로 버튼을 사용할 수 없다는 것을 확신 할 수 있습니다 history.length===0.

그것으로 충분하지 않으면, 당신이 할 수있는 전부는 전화 history.back()이고, 그 후에도 여전히 페이지가로드되면 뒤로 버튼을 사용할 수 없습니다! 물론 뒤로 버튼 사용할 수 있다면 페이지에서 다른 곳으로 이동 한 것입니다. 에서 탐색을 취소 onunload할 수 없으므로 실제로 발생하는 등을 중지하기 위해 할 수있는 모든 작업은에서 무언가를 반환 onbeforeunload하는 것이므로 큰 성가신 프롬프트가 표시됩니다. 그것은 가치가 없어.

실제로 역사와 관련된 일을하는 것은 일반적으로 정말 나쁜 생각입니다. 방문 기록 탐색은 웹 페이지가 아닌 브라우저 크롬 용입니다. "돌아 가기"링크를 추가하면 일반적으로 가치보다 많은 사용자 혼란이 발생합니다.


여기 내가 어떻게했는지.

내가 사용하는 'beforeunload'이벤트를 부울을 설정할 수 있습니다. 그런 다음 'beforeunload'가 시작되었는지 시간 초과를 설정했습니다.

var $window = $(window),
    $trigger = $('.select_your_link'),
    fallback = 'your_fallback_url';
    hasHistory = false;

$window.on('beforeunload', function(){
    hasHistory = true;
});

$trigger.on('click', function(){

    window.history.go(-1);

    setTimeout(function(){
        if (!hasHistory){
            window.location.href = fallback;
        }
    }, 200);

    return false;
});

주요 브라우저 (FF, Chrome, IE11에서 테스트 됨)에서 작동하는 것 같습니다.


내 프로젝트에서 사용하는 스 니펫이 있습니다.

function back(url) {
    if (history.length > 2) {
        // if history is not empty, go back:
        window.History.back();
    } else if (url) {
        // go to specified fallback url:
        window.History.replaceState(null, null, url);
    } else {
        // go home:
        window.History.replaceState(null, null, '/');
    }
}

참고 : History.js사용 하여 브라우저 기록을 관리합니다.


history.length를 숫자 2와 비교하는 이유는 무엇입니까?

Chrome의 시작 페이지는 브라우저 기록에서 첫 번째 항목으로 계산되기 때문입니다.


몇 가지 가능성 history.length과 사용자 행동이 있습니다.

  • User opens new empty tab in the browser and then runs a page. history.length = 2 and we want to disable back() in this case, because user will go to empty tab.
  • User opens the page in new tab by clicking a link somewhere before. history.length = 1 and again we want to disable back() method.
  • And finally, user lands at current page after reloading few pages. history.length > 2 and now back() can be enabled.

Note: I omit case when user lands at current page after clicking link from external website without target="_blank".

Note 2: document.referrer is empty when you open website by typing its address and also when website uses ajax to load subpages, so I discontinued checking this value in the first case.


Be careful with window.history.length because it includes also entries for window.history.forward()

So you may have maybe window.history.length with more than 1 entries, but no history back entries. This means that nothing happens if you fire window.history.back()


history.length is useless as it does not show if user can go back in history. Also different browsers uses initial values 0 or 1 - it depends on browser.

The working solution is to use $(window).on('beforeunload' event, but I'm not sure that it will work if page is loaded via ajax and uses pushState to change window history.

So I've used next solution:

var currentUrl = window.location.href;
window.history.back();
setTimeout(function(){
    // if location was not changed in 100 ms, then there is no history back
    if(currentUrl === window.location.href){
        // redirect to site root
        window.location.href = '/';
    }
}, 100);

I came up with the following approach. It utilizes the onbeforeunload event to detect whether the browser starts leaving the page or not. If it does not in a certain timespan it'll just redirect to the fallback.

var goBack = function goBack(fallback){
    var useFallback = true;

    window.addEventListener("beforeunload", function(){
      useFallback = false;
    });

    window.history.back();

    setTimeout(function(){
        if (useFallback){ window.location.href = fallback; }
    }, 100); 
}

You can call this function using goBack("fallback.example.org").


There is another near perfect solution, taken from another SO answer:

if( (1 < history.length) && document.referrer ) {
    history.back();
}
else {
    // If you can't go back in history, you could perhaps close the window ?
    window.close();
}

Someone reported that it does not work when using target="_blank" but it seems to work for me on Chrome.


Building on the answer here and here. I think, the more conclusive answer is just to check if this is a new page in a new tab.

If the history of the page is more than one, then we can go back to the page previous to the current page. If not, the tab is a newly opened tab and we need to create a new tab.

Differently, to the answers linked, we are not checking for a referrer as a new tab will still have a referrer.

if( (1 < history.length) {
    history.back();
}
else {
    window.close();
}

the browser has back and forward button. I come up a solution on this question. but It will affect browser forward action and cause bug with some browsers.

It works like that: If the browser open a new url, that has never opened, the history.length will be grow.

so you can change hash like

  location.href = '#__transfer__' + new Date().getTime() 

to get a never shown url, then history.length will get the true length.

  var realHistoryLength = history.length - 1

but, It not always work well, and I don't known why ,especially the when url auto jump quickly.


var fallbackUrl = "home.php";
if(history.back() === undefined)
    window.location.href = fallbackUrl;

Solution

'use strict';
function previousPage() {
  if (window.location.pathname.split('/').filter(({ length }) => length > 0).length > 0) {
    window.history.back();
  }
}

Explaination

window.location.pathname will give you the current URI. For instance https://domain/question/1234/i-have-a-problem will give /question/1234/i-have-a-problem. See the documentation about window.location for more informations.

Next, the call to split() will give us all fragments of that URI. so if we take our previous URI, we will have something like ["", "question", "1234", "i-have-a-problem"]. See the documentation about String.prototype.split() for more informations.

The call to filter() is here to filter out the empty string generated by the backward slash. It will basically return only the fragment URI that have a length greater than 1 (non-empty string). So we would have something like ["question", "1234", "i-have-a-question"]. This could have been writen like so:

'use strict';
window.location.pathname.split('/').filter(function(fragment) {
  return fragment.length > 0;
});

See the documentation about Array.prototype.filter() and the Destructuring assignment for more informations.

Now, if the user tries to go back while being on https://domain/, we wont trigger the if-statement, and so wont trigger the window.history.back() method so the user will stay in our website. This URL will be equivalent to [] which has a length of 0, and 0 > 0 is false. Hence, silently failing. Of course, you can log something or have another action if you want.

'use strict';
function previousPage() {
  if (window.location.pathname.split('/').filter(({ length }) => length > 0).length > 0) {
    window.history.back();
  } else {
    alert('You cannot go back any further...');
  }
}

Limitations

Of course, this solution wont work if the browser do not support the History API. Check the documentation to know more about it before using this solution.


I'm not sure if this works and it is completely untested, but try this:

<script type="text/javascript">

    function goBack() {
        history.back();
    }

    if (history.length > 0) { //if there is a history...
        document.getElementsByTagName('button')[].onclick="goBack()"; //assign function "goBack()" to all buttons onClick
    } else {
        die();
    }
</script>

And somewhere in HTML:

<button value="Button1"> //These buttons have no action
<button value="Button2">

EDIT:

당신이 할 수있는 일은 뒤로 기능을 지원하는 브라우저 (모두가 생각하는 것)를 조사 하고이 페이지 에서 발견되고 철저하게 설명 된 표준 JavaScript 브라우저 감지 객체를 사용하는 것 입니다. 그런 다음 두 개의 다른 페이지를 가질 수 있습니다. 하나는 뒤로 버튼과 호환되는 "좋은 브라우저"를위한 것이고 다른 하나는 브라우저를 업데이트하라고 알려주는 "나쁜 브라우저"를위한 것입니다.


window.history.length0 인지 확인하십시오 .

참고 URL : https://stackoverflow.com/questions/3588315/how-to-check-if-the-user-can-go-back-in-browser-history-or-not

반응형