使用Javascript:如果标签或窗口没有历史记录,如何创建一个“返回”链接,将用户带到一个链接?

时间:2022-02-05 04:58:46

EDIT-2: None of the answers seem to work. Not even the one I previously marked as the answer of this question. Any help is appreciated. Thanks.

编辑2:所有的答案似乎都不管用。甚至连我之前标注的答案都没有。任何帮助都是感激。谢谢。

First, I have googled for a how-to on creating a 'Go Back' link that allows the user to return to the previous page, and these are two ways of doing it:

首先,我在谷歌上搜索了如何创建“返回”链接,允许用户返回到上一页,有两种方法:

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

and...

和…

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

Which of these two is a better choice? And why? (Also, please shed some light on browser compatibility.)

这两者中哪一个是更好的选择?,为什么?(同时,请介绍一下浏览器兼容性。)

That's one half of the question. Now if mine is the first page the user is visiting, the 'Go Back' link wouldn't work, right? (As there's no pre-existing history for the window or tab.) In that case, I want the link to fallback and take the user to http://example.com.

这是问题的一半。如果我的是用户访问的第一个页面,“返回”链接就不能用了,对吧?(因为窗口或选项卡没有预先存在的历史记录。)在这种情况下,我希望链接返回到http://example.com。

i.e. if history exists, the user is taken to the previous page, and if it doesn't he's taken to http://example.com.

也就是说,如果历史存在,用户会被带到前一页,如果没有,他就会被带到http://example.com。

How do I do that? Hope someone can help.

我该怎么做呢?希望有人可以帮助你。

EDIT: Please note that I do not know JavaScript, so kindly make your answer explanative. Thanks.

编辑:请注意,我不懂JavaScript,所以请您解释一下。谢谢。

11 个解决方案

#1


31  

You cannot check window.history.length as it contains the amount of pages in you visited in total in a given session:

你不能检查window.history。长度,因为它包含您在给定的会话中访问的页面总数:

window.history.length (Integer)

window.history。长度(整数)

Read-only. Returns the number of elements in the session history, including the currently loaded page. For example, for a page loaded in a new tab this property returns 1. Cite 1

只读的。返回会话历史中元素的数量,包括当前加载的页面。例如,对于新选项卡中加载的页面,此属性返回1。引用1

Lets say a user visits your page, clicks on some links and goes back:

假设用户访问你的页面,点击一些链接,然后返回:

www.mysite.com/index.html <-- first page and now current page                  <----+
www.mysite.com/about.html                                                           |
www.mysite.com/about.html#privacy                                                   | 
www.mysite.com/terms.html <-- user uses backbutton or your provided solution to go back

Now window.history.length is 4. You cannot traverse through the history items due to security reasons. Otherwise on could could read the user's history and get his online banking session id or other sensitive information.

现在window.history。长度是4。由于安全原因,无法遍历历史项。否则,on可以读取用户的历史并获取其在线银行会话id或其他敏感信息。

You can set a timeout, that will enable you to act if the previous page isn't loaded in a given time. However, if the user has a slow Internet connection and the timeout is to short, this method will redirect him to your default location all the time:

您可以设置一个超时,如果在给定的时间没有加载上一个页面,那么就可以执行该操作。但是,如果用户的网络连接速度慢,超时时间短,该方法会一直将用户重定向到您的默认位置:

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>

Note that typeof(document.referrer) !== "string" is important, as browser vendors can disable the referrer due to security reasons (session hashes, custom GET URLs). But if we detect a referrer and it's empty, it's probaly save to say that there's no previous page (see note below). Still there could be some strange browser quirk going on, so it's safer to use the timeout than to use a simple redirection.

请注意,类型(document.referrer) != "string"很重要,因为浏览器供应商可以出于安全原因禁用referrer(会话散列、自定义GET url)。但是如果我们检测到一个引用者,它是空的,那么很可能保存为没有先前的页面(请参阅下面的注释)。仍然可能会出现一些奇怪的浏览器怪癖,所以使用超时比使用简单的重定向更安全。

EDIT: Don't use <a href='#'>...</a>, as this will add another entry to the session history. It's better to use a <span> or some other element. Note that typeof document.referrer is always "string" and not empty if your page is inside of a (i)frame.

编辑:不要使用……,因为这将向会话历史记录添加另一个条目。最好使用或其他元素。注意类文档。如果您的页面位于(i)框架内,则引用者总是“字符串”而不是空的。

See also:

参见:

#2


13  

check window.history.length or simply, history.length

检查window.history。或者只是长度,history.length

EDIT: some browsers start their history with 0, others with 1. adjust accordingly.

编辑:有些浏览器的历史记录以0开头,有些以1开头。相应的调整。

if it has a value of 1, it means it's the first page in that window/tab - then you can have JS redirect you.

如果它的值是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>

#3


9  

both would work the same, its just two different methods to call the same function. Try the following:

这两个函数都是一样的,只是调用同一个函数的两个不同的方法。试试以下:

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

#4


7  

The reason on using the return:false; is well explained on this other question.

使用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>

#5


6  

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

Will go back one page.

将返回一页。

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

Will go back two pages.

将返回两页。

#6


4  

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.

调用history.back(),然后更改位置。如果浏览器能够返回历史记录,它将无法访问下一个语句。如果不能返回,它将返回指定的位置。

#7


2  

The following code did the trick for me.

下面的代码对我很有用。

html:

html:

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

js:

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.

所以,你使用文档。引用设置您来自的页面的域。然后使用windows .location将其与当前url进行比较。

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.

如果它们来自同一个域,则意味着您来自您自己的站点,并将它们发送到windows .history.back()。如果他们不一样,你就从别的地方来,你应该回家或者做你喜欢做的事。

#8


1  

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:

问题是你在检查文件。referer,因为在ff中,它总是返回true,然后导航到http://mysite.com。试试以下:

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;
}

#9


1  

simply use cookies to store your visited page list.

只需使用cookie来存储已访问的页面列表。

and apply some if else.

如果还有其他的。

EDIT: also use ServerVariables HTTP_REFERER.

编辑:也使用服务器变量HTTP_REFERER。

#10


1  

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

您需要检查这两个文档。推荐人和历史。长度就像我对类似问题的回答:https://*.com/a/36645802/1145274

#11


0  

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.

这应该是希望的,所以即使它是他们访问的第一个页面,你在代码中定义的URL也会是他们点击返回时的URL。

#1


31  

You cannot check window.history.length as it contains the amount of pages in you visited in total in a given session:

你不能检查window.history。长度,因为它包含您在给定的会话中访问的页面总数:

window.history.length (Integer)

window.history。长度(整数)

Read-only. Returns the number of elements in the session history, including the currently loaded page. For example, for a page loaded in a new tab this property returns 1. Cite 1

只读的。返回会话历史中元素的数量,包括当前加载的页面。例如,对于新选项卡中加载的页面,此属性返回1。引用1

Lets say a user visits your page, clicks on some links and goes back:

假设用户访问你的页面,点击一些链接,然后返回:

www.mysite.com/index.html <-- first page and now current page                  <----+
www.mysite.com/about.html                                                           |
www.mysite.com/about.html#privacy                                                   | 
www.mysite.com/terms.html <-- user uses backbutton or your provided solution to go back

Now window.history.length is 4. You cannot traverse through the history items due to security reasons. Otherwise on could could read the user's history and get his online banking session id or other sensitive information.

现在window.history。长度是4。由于安全原因,无法遍历历史项。否则,on可以读取用户的历史并获取其在线银行会话id或其他敏感信息。

You can set a timeout, that will enable you to act if the previous page isn't loaded in a given time. However, if the user has a slow Internet connection and the timeout is to short, this method will redirect him to your default location all the time:

您可以设置一个超时,如果在给定的时间没有加载上一个页面,那么就可以执行该操作。但是,如果用户的网络连接速度慢,超时时间短,该方法会一直将用户重定向到您的默认位置:

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>

Note that typeof(document.referrer) !== "string" is important, as browser vendors can disable the referrer due to security reasons (session hashes, custom GET URLs). But if we detect a referrer and it's empty, it's probaly save to say that there's no previous page (see note below). Still there could be some strange browser quirk going on, so it's safer to use the timeout than to use a simple redirection.

请注意,类型(document.referrer) != "string"很重要,因为浏览器供应商可以出于安全原因禁用referrer(会话散列、自定义GET url)。但是如果我们检测到一个引用者,它是空的,那么很可能保存为没有先前的页面(请参阅下面的注释)。仍然可能会出现一些奇怪的浏览器怪癖,所以使用超时比使用简单的重定向更安全。

EDIT: Don't use <a href='#'>...</a>, as this will add another entry to the session history. It's better to use a <span> or some other element. Note that typeof document.referrer is always "string" and not empty if your page is inside of a (i)frame.

编辑:不要使用……,因为这将向会话历史记录添加另一个条目。最好使用或其他元素。注意类文档。如果您的页面位于(i)框架内,则引用者总是“字符串”而不是空的。

See also:

参见:

#2


13  

check window.history.length or simply, history.length

检查window.history。或者只是长度,history.length

EDIT: some browsers start their history with 0, others with 1. adjust accordingly.

编辑:有些浏览器的历史记录以0开头,有些以1开头。相应的调整。

if it has a value of 1, it means it's the first page in that window/tab - then you can have JS redirect you.

如果它的值是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>

#3


9  

both would work the same, its just two different methods to call the same function. Try the following:

这两个函数都是一样的,只是调用同一个函数的两个不同的方法。试试以下:

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

#4


7  

The reason on using the return:false; is well explained on this other question.

使用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>

#5


6  

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

Will go back one page.

将返回一页。

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

Will go back two pages.

将返回两页。

#6


4  

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.

调用history.back(),然后更改位置。如果浏览器能够返回历史记录,它将无法访问下一个语句。如果不能返回,它将返回指定的位置。

#7


2  

The following code did the trick for me.

下面的代码对我很有用。

html:

html:

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

js:

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.

所以,你使用文档。引用设置您来自的页面的域。然后使用windows .location将其与当前url进行比较。

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.

如果它们来自同一个域,则意味着您来自您自己的站点,并将它们发送到windows .history.back()。如果他们不一样,你就从别的地方来,你应该回家或者做你喜欢做的事。

#8


1  

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:

问题是你在检查文件。referer,因为在ff中,它总是返回true,然后导航到http://mysite.com。试试以下:

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;
}

#9


1  

simply use cookies to store your visited page list.

只需使用cookie来存储已访问的页面列表。

and apply some if else.

如果还有其他的。

EDIT: also use ServerVariables HTTP_REFERER.

编辑:也使用服务器变量HTTP_REFERER。

#10


1  

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

您需要检查这两个文档。推荐人和历史。长度就像我对类似问题的回答:https://*.com/a/36645802/1145274

#11


0  

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.

这应该是希望的,所以即使它是他们访问的第一个页面,你在代码中定义的URL也会是他们点击返回时的URL。