I want using JavaScript to see if there is history or not, I mean if the back button is available on the browser or not.
我想使用JavaScript来查看是否有历史,我的意思是返回按钮是否在浏览器上可用。
15 个解决方案
#1
83
Short answer: You can't.
简短的回答是:你不能。
Technically there is an accurate way, which would be checking the property:
技术上有一种精确的方法,那就是检查财产:
history.previous
However, it won't work. The problem with this is that in most browsers this is considered a security violation and usually just returns undefined.
然而,它不会工作。问题是,在大多数浏览器中,这被认为是安全违规,通常只返回未定义的。
history.length
Is a property that others have suggested...
However, the length doesn't work completely because it doesn't indicate where in the history you are. Additionally, it doesn't always start at the same number. A browser not set to have a landing page, for example, starts at 0 while another browser that uses a langing page will start at 1.
是其他人建议的财产。然而,长度并不能完全起作用,因为它不能指明你在历史上的位置。此外,它并不总是以相同的数字开始。例如,未设置为着陆页的浏览器从0开始,而使用langing页面的浏览器从1开始。
Most of the time a link is added that calls:
大多数时候,会添加一个链接来调用:
history.back();
or
或
history.go(-1);
and it's just expected that if you can't go back then clicking the link does nothing.
如果你不能返回,点击链接就什么都做不了。
#2
65
There is another way to check - check the referrer. The first page usually will have an empty referrer...
还有另一种检查方法——检查推荐人。第一页通常会有一个空的推荐人……
if (document.referrer == "") {
window.close()
} else {
history.back()
}
#3
36
My code let the browser go back one page, and if that fails it loads a fallback url. It also detect hashtags changes.
我的代码允许浏览器返回一个页面,如果失败,它将加载回退url。它还检测hashtags更改。
When the back button wasn't available, the fallback url will be loaded after 500 ms, so the browser has time enough to load the previous page. Loading the fallback url right after window.history.go(-1);
would cause the browser to use the fallback url, because the js script didn't stop yet.
当后退按钮不可用时,回退url将在500毫秒后加载,因此浏览器有足够的时间加载上一页。在window.history.go(-1)之后加载回退url;会导致浏览器使用回退url,因为js脚本还没有停止。
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);
}
#4
10
this seems to do the trick:
这似乎很管用:
function goBackOrClose() {
window.history.back();
window.close();
//or if you are not interested in closing the window, do something else here
//e.g.
theBrowserCantGoBack();
}
Call history.back() and then window.close(). 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 close the window.
调用history.back()然后window.close()。如果浏览器能够返回历史记录,它将无法访问下一个语句。如果它不能回去,它就会关上窗户。
However, please note that if the page has been reached by typing a url, then firefox wont allow the script to close the window.
但是,请注意,如果通过输入url来访问页面,那么firefox不允许脚本关闭窗口。
#5
9
You can't directly check whether the back button is usable. You can look at history.length>0
, but that will hold true if there are pages ahead of the current page as well. You can only be sure that the back button is unusable when history.length===0
.
您不能直接检查back按钮是否可用。你可以看看历史。长度>0,但是如果当前页面前面也有页面,那么这个值仍然成立。您只能确定,当history.length== 0时,后退按钮是不可用的。
If that's not good enough, about all you can do is call history.back()
and, if your page is still loaded afterwards, the back button is unavailable! Of course that means if the back button is available, you've just navigated away from the page. You aren't allowed to cancel the navigation in onunload
, so about all you can do to stop the back actually happening is to return something from onbeforeunload
, which will result in a big annoying prompt appearing. It's not worth it.
如果这还不够好,那么您所能做的就是调用history.back(),如果您的页面之后仍然被加载,那么back按钮是不可用的!当然,这意味着如果返回按钮是可用的,那么您就可以从页面导航了。您不允许取消onunload中的导航,所以您可以做的是阻止实际发生的事情是返回onbeforeunload中的某个东西,这将导致出现一个巨大的恼人的提示。这是不值得的。
In fact it's normally a Really Bad Idea to be doing anything with the history. History navigation is for browser chrome, not web pages. Adding “go back” links typically causes more user confusion than it's worth.
事实上,用历史做任何事通常都是一个非常糟糕的主意。历史导航是为浏览器chrome而不是网页。添加“返回”链接通常会导致更多的用户困惑,而不是它的价值。
#6
7
Here is how i did it.
我是这样做的。
I used the 'beforeunload' event to set a boolean. Then I set a timeout to watch if the 'beforeunload' fired.
我使用“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;
});
Seems to work in major browsers (tested FF, Chrome, IE11 so far).
似乎在主要的浏览器(测试过的FF、Chrome、IE11)中都可以使用。
#7
5
There is a snippet I use in my projects:
在我的项目中有一个片段:
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, '/');
}
}
FYI: I use History.js to manage browser history.
通知你:我使用的历史。js来管理浏览器历史。
Why to compare history.length to number 2?
比较历史的原因。长度2号吗?
Because Chrome's startpage is counted as first item in the browser's history.
因为Chrome的startpage是浏览器历史上的第一项。
There are few possibilities of history.length
and user's behaviour:
历史的可能性很少。长度和用户的行为:
- User opens new empty tab in the browser and then runs a page.
history.length = 2
and we want to disableback()
in this case, because user will go to empty tab. - 用户在浏览器中打开新的空选项卡,然后运行一个页面。历史。length = 2,在本例中我们要禁用back(),因为user将转到empty选项卡。
- User opens the page in new tab by clicking a link somewhere before.
history.length = 1
and again we want to disableback()
method. - 用户通过单击之前某个地方的链接打开new选项卡中的页面。历史。length = 1,我们要禁用back()方法。
- And finally, user lands at current page after reloading few pages.
history.length > 2
and nowback()
can be enabled. - 最后,用户在重新加载了几个页面后,会到达当前页面。历史。可以启用长度> 2和back()。
Note: I omit case when user lands at current page after clicking link from external website without target="_blank"
.
注意:我省略了用户在点击没有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.
注2:文档。当你打开网站的时候,你可以输入它的地址,当你的网站使用ajax加载子页面时,你会发现它是空的,所以我在第一种情况下就不再检查这个值了。
#8
3
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.
历史。长度是无用的,因为它不显示用户是否可以返回历史。不同的浏览器使用初始值0或1——这取决于浏览器。
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.
可用的解决方案是使用$(窗口)。on('beforeunload'事件),但我不确定如果页面通过ajax加载,并使用pushState来更改窗口历史,它是否会起作用。
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);
#9
2
Be careful with window.history.length
beacuse it includes also entries for window.history.forward()
小心window.history。长度,因为它还包括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()
所以你可能有window。history。包含一个以上条目的长度,但是没有历史返回条目。这意味着如果你按了windows .history.back()
#10
1
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.
我想到了以下方法。它利用onbeforeunload事件来检测浏览器是否开始离开页面。如果在特定的时间内没有,它将直接重定向到回退。
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")
.
您可以使用goBack调用这个函数(“fallback.example.org”)。
#11
0
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.
浏览器有后退和前进按钮。我对这个问题想出了一个解决办法。但它会影响浏览器的转发行为,并导致某些浏览器出现bug。
It works like that: If the browser open a new url, that has never opened, the history.length will be grow.
它是这样工作的:如果浏览器打开一个从未打开过的新url,历史记录。长度将增加。
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.
要获取一个从未显示的url,则需要历史记录。长度将得到真正的长度。
var realHistoryLength = history.length - 1
but, It not always work well, and I don't known why ,especially the when url auto jump quickly.
但是,它并不总是工作得很好,我不知道为什么,尤其是当url自动跳转得很快的时候。
#12
0
There is another near perfect solution, taken from another SO answer:
还有另一个近乎完美的解决方案,取自另一个SO答案:
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.
有人报告说,在使用target=“_blank”时,它并不起作用,但它在Chrome上似乎对我有用。
#13
-1
var fallbackUrl = "home.php";
if(history.back() === undefined)
window.location.href = fallbackUrl;
#14
-6
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:
在HTML:
<button value="Button1"> //These buttons have no action
<button value="Button2">
EDIT:
What you can also do is to research what browsers support the back function (I think they all do) and use the standard JavaScript browser detection object found, and described thoroughly, on this page. Then you can have 2 different pages: one for the "good browsers" compatible with the back button and one for the "bad browsers" telling them to go update their browser
您还可以研究哪些浏览器支持back函数(我认为它们都支持),并使用在此页面上找到并详细描述的标准JavaScript浏览器检测对象。然后你可以有两个不同的页面:一个用于与后退按钮兼容的“好浏览器”,另一个用于“坏浏览器”,告诉他们去更新他们的浏览器
#15
-7
Check if window.history.length
is equal to 0.
检查是否window.history。长度等于0。
#1
83
Short answer: You can't.
简短的回答是:你不能。
Technically there is an accurate way, which would be checking the property:
技术上有一种精确的方法,那就是检查财产:
history.previous
However, it won't work. The problem with this is that in most browsers this is considered a security violation and usually just returns undefined.
然而,它不会工作。问题是,在大多数浏览器中,这被认为是安全违规,通常只返回未定义的。
history.length
Is a property that others have suggested...
However, the length doesn't work completely because it doesn't indicate where in the history you are. Additionally, it doesn't always start at the same number. A browser not set to have a landing page, for example, starts at 0 while another browser that uses a langing page will start at 1.
是其他人建议的财产。然而,长度并不能完全起作用,因为它不能指明你在历史上的位置。此外,它并不总是以相同的数字开始。例如,未设置为着陆页的浏览器从0开始,而使用langing页面的浏览器从1开始。
Most of the time a link is added that calls:
大多数时候,会添加一个链接来调用:
history.back();
or
或
history.go(-1);
and it's just expected that if you can't go back then clicking the link does nothing.
如果你不能返回,点击链接就什么都做不了。
#2
65
There is another way to check - check the referrer. The first page usually will have an empty referrer...
还有另一种检查方法——检查推荐人。第一页通常会有一个空的推荐人……
if (document.referrer == "") {
window.close()
} else {
history.back()
}
#3
36
My code let the browser go back one page, and if that fails it loads a fallback url. It also detect hashtags changes.
我的代码允许浏览器返回一个页面,如果失败,它将加载回退url。它还检测hashtags更改。
When the back button wasn't available, the fallback url will be loaded after 500 ms, so the browser has time enough to load the previous page. Loading the fallback url right after window.history.go(-1);
would cause the browser to use the fallback url, because the js script didn't stop yet.
当后退按钮不可用时,回退url将在500毫秒后加载,因此浏览器有足够的时间加载上一页。在window.history.go(-1)之后加载回退url;会导致浏览器使用回退url,因为js脚本还没有停止。
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);
}
#4
10
this seems to do the trick:
这似乎很管用:
function goBackOrClose() {
window.history.back();
window.close();
//or if you are not interested in closing the window, do something else here
//e.g.
theBrowserCantGoBack();
}
Call history.back() and then window.close(). 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 close the window.
调用history.back()然后window.close()。如果浏览器能够返回历史记录,它将无法访问下一个语句。如果它不能回去,它就会关上窗户。
However, please note that if the page has been reached by typing a url, then firefox wont allow the script to close the window.
但是,请注意,如果通过输入url来访问页面,那么firefox不允许脚本关闭窗口。
#5
9
You can't directly check whether the back button is usable. You can look at history.length>0
, but that will hold true if there are pages ahead of the current page as well. You can only be sure that the back button is unusable when history.length===0
.
您不能直接检查back按钮是否可用。你可以看看历史。长度>0,但是如果当前页面前面也有页面,那么这个值仍然成立。您只能确定,当history.length== 0时,后退按钮是不可用的。
If that's not good enough, about all you can do is call history.back()
and, if your page is still loaded afterwards, the back button is unavailable! Of course that means if the back button is available, you've just navigated away from the page. You aren't allowed to cancel the navigation in onunload
, so about all you can do to stop the back actually happening is to return something from onbeforeunload
, which will result in a big annoying prompt appearing. It's not worth it.
如果这还不够好,那么您所能做的就是调用history.back(),如果您的页面之后仍然被加载,那么back按钮是不可用的!当然,这意味着如果返回按钮是可用的,那么您就可以从页面导航了。您不允许取消onunload中的导航,所以您可以做的是阻止实际发生的事情是返回onbeforeunload中的某个东西,这将导致出现一个巨大的恼人的提示。这是不值得的。
In fact it's normally a Really Bad Idea to be doing anything with the history. History navigation is for browser chrome, not web pages. Adding “go back” links typically causes more user confusion than it's worth.
事实上,用历史做任何事通常都是一个非常糟糕的主意。历史导航是为浏览器chrome而不是网页。添加“返回”链接通常会导致更多的用户困惑,而不是它的价值。
#6
7
Here is how i did it.
我是这样做的。
I used the 'beforeunload' event to set a boolean. Then I set a timeout to watch if the 'beforeunload' fired.
我使用“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;
});
Seems to work in major browsers (tested FF, Chrome, IE11 so far).
似乎在主要的浏览器(测试过的FF、Chrome、IE11)中都可以使用。
#7
5
There is a snippet I use in my projects:
在我的项目中有一个片段:
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, '/');
}
}
FYI: I use History.js to manage browser history.
通知你:我使用的历史。js来管理浏览器历史。
Why to compare history.length to number 2?
比较历史的原因。长度2号吗?
Because Chrome's startpage is counted as first item in the browser's history.
因为Chrome的startpage是浏览器历史上的第一项。
There are few possibilities of history.length
and user's behaviour:
历史的可能性很少。长度和用户的行为:
- User opens new empty tab in the browser and then runs a page.
history.length = 2
and we want to disableback()
in this case, because user will go to empty tab. - 用户在浏览器中打开新的空选项卡,然后运行一个页面。历史。length = 2,在本例中我们要禁用back(),因为user将转到empty选项卡。
- User opens the page in new tab by clicking a link somewhere before.
history.length = 1
and again we want to disableback()
method. - 用户通过单击之前某个地方的链接打开new选项卡中的页面。历史。length = 1,我们要禁用back()方法。
- And finally, user lands at current page after reloading few pages.
history.length > 2
and nowback()
can be enabled. - 最后,用户在重新加载了几个页面后,会到达当前页面。历史。可以启用长度> 2和back()。
Note: I omit case when user lands at current page after clicking link from external website without target="_blank"
.
注意:我省略了用户在点击没有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.
注2:文档。当你打开网站的时候,你可以输入它的地址,当你的网站使用ajax加载子页面时,你会发现它是空的,所以我在第一种情况下就不再检查这个值了。
#8
3
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.
历史。长度是无用的,因为它不显示用户是否可以返回历史。不同的浏览器使用初始值0或1——这取决于浏览器。
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.
可用的解决方案是使用$(窗口)。on('beforeunload'事件),但我不确定如果页面通过ajax加载,并使用pushState来更改窗口历史,它是否会起作用。
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);
#9
2
Be careful with window.history.length
beacuse it includes also entries for window.history.forward()
小心window.history。长度,因为它还包括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()
所以你可能有window。history。包含一个以上条目的长度,但是没有历史返回条目。这意味着如果你按了windows .history.back()
#10
1
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.
我想到了以下方法。它利用onbeforeunload事件来检测浏览器是否开始离开页面。如果在特定的时间内没有,它将直接重定向到回退。
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")
.
您可以使用goBack调用这个函数(“fallback.example.org”)。
#11
0
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.
浏览器有后退和前进按钮。我对这个问题想出了一个解决办法。但它会影响浏览器的转发行为,并导致某些浏览器出现bug。
It works like that: If the browser open a new url, that has never opened, the history.length will be grow.
它是这样工作的:如果浏览器打开一个从未打开过的新url,历史记录。长度将增加。
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.
要获取一个从未显示的url,则需要历史记录。长度将得到真正的长度。
var realHistoryLength = history.length - 1
but, It not always work well, and I don't known why ,especially the when url auto jump quickly.
但是,它并不总是工作得很好,我不知道为什么,尤其是当url自动跳转得很快的时候。
#12
0
There is another near perfect solution, taken from another SO answer:
还有另一个近乎完美的解决方案,取自另一个SO答案:
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.
有人报告说,在使用target=“_blank”时,它并不起作用,但它在Chrome上似乎对我有用。
#13
-1
var fallbackUrl = "home.php";
if(history.back() === undefined)
window.location.href = fallbackUrl;
#14
-6
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:
在HTML:
<button value="Button1"> //These buttons have no action
<button value="Button2">
EDIT:
What you can also do is to research what browsers support the back function (I think they all do) and use the standard JavaScript browser detection object found, and described thoroughly, on this page. Then you can have 2 different pages: one for the "good browsers" compatible with the back button and one for the "bad browsers" telling them to go update their browser
您还可以研究哪些浏览器支持back函数(我认为它们都支持),并使用在此页面上找到并详细描述的标准JavaScript浏览器检测对象。然后你可以有两个不同的页面:一个用于与后退按钮兼容的“好浏览器”,另一个用于“坏浏览器”,告诉他们去更新他们的浏览器
#15
-7
Check if window.history.length
is equal to 0.
检查是否window.history。长度等于0。