Development Tip

자바 스크립트 사용 : 탭이나 창에 대한 기록이없는 경우 사용자를 링크로 연결하는 '뒤로'링크를 만드는 방법은 무엇입니까?

yourdevel 2020. 12. 12. 12:34
반응형

자바 스크립트 사용 : 탭이나 창에 대한 기록이없는 경우 사용자를 링크로 연결하는 '뒤로'링크를 만드는 방법은 무엇입니까?


편집 -2 : 답변이 작동하지 않는 것 같습니다. 이전에이 질문에 대한 답변으로 표시 한 것도 아닙니다. 도움을 주시면 감사하겠습니다. 감사.

먼저, 사용자가 이전 페이지로 돌아갈 수있는 '돌아 가기'링크를 만드는 방법에 대해 검색해 보았습니다. 두 가지 방법이 있습니다.

<a href="javascript:history.go(-1)">[Go Back]</a>

과...

<a href="#" onclick="history.go(-1);return false;">[Go Back]</a>

이 두 가지 중 어느 것이 더 나은 선택입니까? 그리고 왜? (또한 브라우저 호환성에 대해 설명 해주세요.)

그것은 질문의 절반입니다. 이제 내 페이지가 사용자가 방문하는 첫 페이지 인 경우 '돌아 가기'링크가 작동하지 않습니다. (창이나 탭에 대한 기존 기록이 없기 때문에)이 경우 링크를 대체하고 사용자를 http://example.com으로 이동 하고 싶습니다 .

즉, 기록이 존재하는 경우 사용자는 이전 페이지로 이동하고 그렇지 않은 경우 http://example.com으로 이동 합니다.

어떻게하나요? 누군가가 도울 수 있기를 바랍니다.

편집 : 나는 JavaScript를 모른다는 점에 유의하십시오. 그러니 친절하게 답변하십시오. 감사.


window.history.length주어진 세션에서 총 방문한 페이지의 양이 포함되어 있으므로 확인할 수 없습니다 .

window.history.length (정수)

읽기 전용. 현재로드 된 페이지를 포함하여 세션 기록의 요소 수를 반환합니다. 예를 들어, 새 탭에로드 된 페이지의 경우이 속성은 1을 반환합니다. Cite 1

사용자가 페이지를 방문하고 일부 링크를 클릭 한 후 다시 돌아 간다고 가정 해 보겠습니다.

www.mysite.com/index.html <-첫 페이지와 현재 페이지 <---- +
www.mysite.com/about.html |
www.mysite.com/about.html#privacy | 
www.mysite.com/terms.html <-사용자는 뒤로 가기 버튼 또는 제공된 솔루션을 사용하여 뒤로 이동합니다.

현재 window.history.length는 4입니다. 보안상의 이유로 기록 항목을 탐색 할 수 없습니다. 그렇지 않으면 사용자의 기록을 읽고 온라인 뱅킹 세션 ID 또는 기타 민감한 정보를 얻을 수 있습니다.

시간 제한을 설정하면 주어진 시간에 이전 페이지가로드되지 않은 경우 작업을 수행 할 수 있습니다. 그러나 사용자의 인터넷 연결 속도가 느리고 제한 시간이 짧은 경우이 방법은 항상 사용자를 기본 위치로 리디렉션합니다.

window.goBack = function (e){
    var defaultLocation = "http://www.mysite.com";
    var oldHash = window.location.hash;

    history.back(); // Try to go back

    var newHash = window.location.hash;

    /* If the previous page hasn't been loaded in a given time (in this case
    * 1000ms) the user is redirected to the default location given above.
    * This enables you to redirect the user to another page.
    *
    * However, you should check whether there was a referrer to the current
    * site. This is a good indicator for a previous entry in the history
    * session.
    *
    * Also you should check whether the old location differs only in the hash,
    * e.g. /index.html#top --> /index.html# shouldn't redirect to the default
    * location.
    */

    if(
        newHash === oldHash &&
        (typeof(document.referrer) !== "string" || document.referrer  === "")
    ){
        window.setTimeout(function(){
            // redirect to default location
            window.location.href = defaultLocation;
        },1000); // set timeout in ms
    }
    if(e){
        if(e.preventDefault)
            e.preventDefault();
        if(e.preventPropagation)
            e.preventPropagation();
    }
    return false; // stop event propagation and browser default event
}
<span class="goback" onclick="goBack();">Go back!</span>

참고 typeof(document.referrer) !== "string"브라우저 벤더는 보안상의 이유 (세션 해시, 사용자 정의 GET URL을)에 참조 페이지를 비활성화 할 수 있습니다으로 중요하다. 그러나 리퍼러를 감지하고 비어있는 경우 이전 페이지가 없다고 말할 수 있습니다 (아래 참고 참조). 여전히 이상한 브라우저 문제가 발생할 수 있으므로 간단한 리디렉션을 사용하는 것보다 시간 제한을 사용하는 것이 더 안전합니다.

편집 :<a href='#'>...</a> 세션 기록에 다른 항목을 추가 하므로을 사용하지 마십시오 . <span>또는 다른 요소 를 사용하는 것이 좋습니다 . 참고 typeof document.referrer항상 "string"페이지가 내부 (I) 프레임의 경우가 아닌 빈.

또한보십시오:


확인 window.history.length하거나 간단히history.length

편집 : 일부 브라우저는 기록을 0으로 시작하고 다른 브라우저는 1로 시작합니다.

값이 1이면 해당 창 / 탭의 첫 페이지임을 의미합니다. 그러면 JS가 리디렉션하도록 할 수 있습니다.

<script>
    function backAway(){
        //if it was the first page
        if(history.length === 1){
            window.location = "http://www.mysite.com/"
        } else {
            history.back();
        }
    }
</script>

<a href="#" onClick="backAway()">Back</a>

둘 다 동일하게 작동하며 동일한 함수를 호출하는 두 가지 다른 방법입니다. 다음을 시도하십시오.

<a href="javascript:history.back();">[Go Back]</a>

echo "<p><a href=\"javascript:history.go(-1)\" title=\"Return to previous page\">&laquo;Go back</a></p>";

한 페이지 뒤로 이동합니다.

echo "<p><a href=\"javascript:history.go(-2)\" title=\"Return to previous page\">&laquo;Go back</a></p>";

두 페이지 뒤로 이동합니다.


를 사용하는 이유 return:false;는이 다른 질문 에 잘 설명되어 있습니다.

For the other issue, you can check for the referrer to see if it is empty:

    function backAway(){
        if (document.referrer == "") { //alternatively, window.history.length == 0
            window.location = "http://www.example.com";
        } else {
            history.back();
        }
    }

<a href="#" onClick="backAway()">Back Button Here.</a>

this seems to do the trick:

function goBackOrGoToUrl() {    

    window.history.back();
    window.location = "http://example.com";

}

Call history.back() and then change the location. If the browser is able to go back in history it won't be able to get to the next statement. If it's not able to go back, it'll go to the location specified.


The following code did the trick for me.

html:

<div class="back" onclick="goBackOrGoHome()">
  Back
</div>

js:

home_url = [YOUR BASE URL];

pathArray = document.referrer.split( '/' );
protocol = pathArray[0];
host = pathArray[2];

url_before = protocol + '//' + host;

url_now = window.location.protocol + "//" + window.location.host;


function goBackOrGoHome(){
  if ( url_before == url_now) {
    window.history.back();    
  }else{
    window.location = home_url;
  };
}

So, you use document.referrer to set the domain of the page you come from. Then you compare that with your current url using window.location.

If they are from the same domain, it means you are coming from your own site and you send them window.history.back(). If they are not the same, you are coming from somewhere else and you should redirect home or do whatever you like.


Added a new answer to display the code formatted:

The thing is that you were checking for document.referer, because you were in ff it was returning always true, then it was navigating to http://mysite.com. Try the following:

function backAway(){
    if (document.referrer) {
        //firefox, chrome, etc..
        i = 0;
    } else {
        // under ie
        i = 1;
    }
    if (history.length>i)
    {
        // there are items in history property
        history.back();
    } else {
        window.location = 'http://www.mysite.com/';
    }
    return false;
}

simply use cookies to store your visited page list.

and apply some if else.

EDIT: also use ServerVariables HTTP_REFERER.


You need to check both document.referrer and history.length like in my answer to similar question here: https://stackoverflow.com/a/36645802/1145274


How about using the history replacement function to add the site into the browsers history?

Try executing the following as soon as the window loads-

history.replaceState("example", "title", "http://www.example.com");

This should hopefully make it so even if it is the first page they have accessed, the URL you define in the code will be what they're taken to when they click back.


You should use window variable - window.referrer. This variable contains the last page the user visited if they got to the current page by clicking a link For example:

  function goBack() {
    if(document.referrer) {
      window.location.href = document.referrer;

      return;
    } 

    window.location.pathname = '/';
  }

This code redirect user to previous page if this is exist and redirect user to homepage if there isn't previous url

참고URL : https://stackoverflow.com/questions/9756159/using-javascript-how-to-create-a-go-back-link-that-takes-the-user-to-a-link-i

반응형