Javascript 使用浏览器后退按钮时如何强制重新加载页面?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43043113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to force reloading a page when using browser back button?
提问by John Doeherskij
I need to somehow detect that the user has pressed a browsers back button and reload the page with refresh (reloading the content and CSS) using jquery.
我需要以某种方式检测用户是否按下了浏览器的后退按钮并使用 jquery 刷新页面(重新加载内容和 CSS)。
How to detect such action via jquery?
如何通过 jquery 检测此类操作?
Because right now some elements are not reloaded if I use the back button in a browser. But if I use links in the website everything is refreshed and showed correctly.
因为现在如果我在浏览器中使用后退按钮,则不会重新加载某些元素。但是,如果我使用网站中的链接,一切都会刷新并正确显示。
IMPORTANT!
重要的!
Some people have probably misunderstood what I want. I don't want to refresh the current page. I want to refresh the page that is loaded after I press the back button. here is what I mean in a more detailed way:
有些人可能误解了我想要什么。我不想刷新当前页面。我想刷新按后退按钮后加载的页面。这是我更详细的意思:
- user is visiting page1.
- while on page1 - he clicks on a link to page2.
- he is redirected to the page2
- now (Important part!) he clicks on the back button in browser because he wants to go back to page1
- he is back on the page1 - and now the page1 is being reloaded and something is alerted like "You are back!"
- 用户正在访问第 1 页。
- 在第 1 页时 - 他单击了指向第 2 页的链接。
- 他被重定向到 page2
- 现在(重要的部分!)他点击浏览器中的后退按钮,因为他想回到第 1 页
- 他回到了第 1 页 - 现在正在重新加载第 1 页,并且出现诸如“您回来了!”之类的警报。
回答by Leonid Vasilev
You can use pageshowevent to handle situation when browser navigates to your page through history traversal:
pageshow当浏览器通过历史遍历导航到您的页面时,您可以使用事件来处理情况:
window.addEventListener( "pageshow", function ( event ) {
var historyTraversal = event.persisted ||
( typeof window.performance != "undefined" &&
window.performance.navigation.type === 2 );
if ( historyTraversal ) {
// Handle page restore.
window.location.reload();
}
});
Note that HTTP cache may be involved too. You need to set proper cache related HTTP headers on server to cache only those resources that need to be cached. You can also do forced reload to instuct browser to ignore HTTP cache: window.location.reload( true ). But I don't think that it is best solution.
请注意,也可能涉及 HTTP 缓存。您需要在服务器上设置适当的缓存相关 HTTP 标头以仅缓存那些需要缓存的资源。您还可以强制重新加载以指示浏览器忽略 HTTP 缓存:window.location.reload( true )。但我不认为这是最好的解决方案。
For more information check:
有关更多信息,请检查:
- Working with BFCachearticle on MDN
- WebKit Page Cache II – The unload Eventby Brady Eidson
- pageshowevent reference on MDN
- Ajax, back button and DOM updatesquestion
- JavaScript - bfcache/pageshow event - event.persisted always set to false?question
- 在 MDN 上使用 BFCache文章
- WebKit 页面缓存 II –Brady Eidson的卸载事件
- MDN 上的pageshow事件参考
- Ajax、后退按钮和 DOM 更新问题
- JavaScript - bfcache/pageshow 事件 - event.persisted 总是设置为 false?题
回答by James
It's been a while since this was posted but I found a more elegant solution if you are not needing to support old browsers.
自发布以来已经有一段时间了,但如果您不需要支持旧浏览器,我找到了一个更优雅的解决方案。
You can do a check with
你可以做一个检查
performance.navigation.type
Documentation including browser support is here: https://developer.mozilla.org/en-US/docs/Web/API/Performance/navigation
包括浏览器支持在内的文档在这里:https: //developer.mozilla.org/en-US/docs/Web/API/Performance/navigation
So to see if the page was loaded from history using back you can do
因此,要查看页面是否是使用 back 从历史记录中加载的,您可以执行以下操作
if(performance.navigation.type == 2){
location.reload(true);
}
The 2indicates the page was accessed by navigating into the history. Other possibilities are-
该2指示页面被导航到历史访问。其他可能性是——
0:The page was accessed by following a link, a bookmark, a form submission, or a script, or by typing the URL in the address bar.
0:通过点击链接、书签、表单提交或脚本,或通过在地址栏中键入 URL 来访问该页面。
1:The page was accessed by clicking the Reload button or via the Location.reload() method.
1:该页面是通过单击重新加载按钮或通过 Location.reload() 方法访问的。
255:Any other way
255:任何其他方式
These are detailed here: https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigation
这些在这里有详细说明:https: //developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigation
回答by Francesco
Just use jquery :
只需使用 jquery :
jQuery( document ).ready(function( $ ) {
//Use this inside your document ready jQuery
$(window).on('popstate', function() {
location.reload(true);
});
});
The above will work 100% when back or forward button has been clicked using ajax as well.
当使用 ajax 单击后退或前进按钮时,上述内容将 100% 工作。
if it doesn't, there must be a misconfiguration in a different part of the script.
如果没有,则脚本的不同部分中一定存在错误配置。
For example it might not reload if something like one of the example in the previous post is used window.history.pushState('', null, './');
例如,如果使用上一篇文章中的示例之一,它可能不会重新加载 window.history.pushState('', null, './');
so when you do use history.pushState();make sure you use it properly.
所以当你确实使用时,请history.pushState();确保正确使用它。
Suggestion in most cases you will just need:
在大多数情况下,您只需要以下建议:
history.pushState(url, '', url);
No window.history... and make sure urlis defined.
没有 window.history... 并确保定义了url。
Hope that helps..
希望有帮助..
回答by LuTHieR
Since performance.navigationis now deprecated, you can try this:
由于performance.navigation现在已弃用,您可以尝试以下操作:
var perfEntries = performance.getEntriesByType("navigation");
if (perfEntries[0].type === "back_forward") {
location.reload(true);
}
回答by Dhiraj
You should use a hidden input as a refresh indicator, with a value of "no":
您应该使用隐藏输入作为刷新指示器,值为“no”:
<input type="hidden" id="refresh" value="no">
Now using jQuery, you can check its value:
现在使用 jQuery,你可以检查它的值:
$(document).ready(function(e) {
var $input = $('#refresh');
$input.val() == 'yes' ? location.reload(true) : $input.val('yes');
});
When you click on the back button, the values in hidden fields retain the same value as when you originally left the page.
当您单击后退按钮时,隐藏字段中的值保留与您最初离开页面时相同的值。
So the first time you load the page, the input's value would be "no". When you return to the page, it'll be "yes" and your JavaScript code will trigger a refresh.
所以第一次加载页面时,输入的值为“no”。当您返回该页面时,它会是“是”并且您的 JavaScript 代码将触发刷新。
回答by Marlon
An alternative that solved the problem to me is to disable cache for the page. That make the browser to get the page from the server instead of using a cached version:
对我来说解决问题的另一种方法是禁用页面缓存。这使浏览器从服务器获取页面而不是使用缓存版本:
Response.AppendHeader("Cache-Control","no-cache, no-store, must-revalidate");
Response.AppendHeader("Pragma", "no-cache");
Response.AppendHeader("Expires", "0");
回答by Anton Stepanenkov
Reload is easy. You should use:
重新加载很容易。你应该使用:
location.reload(true);
And detecting back is :
检测回来是:
window.history.pushState('', null, './');
$(window).on('popstate', function() {
location.reload(true);
});
回答by Rajesh Kharatmol
Use following meta tag in your html header file, This works for me.
在您的 html 头文件中使用以下元标记,这对我有用。
<meta http-equiv="Pragma" content="no-cache">
回答by muhammed aslam
I found the best answer and it is working perfectly for me
我找到了最好的答案,它非常适合我
just use this simple script in your link
只需在您的链接中使用这个简单的脚本
<A HREF="javascript:history.go(0)">next page</A>
or the button click event
或者按钮点击事件
<INPUT TYPE="button" onClick="history.go(0)" VALUE="next page">
when you use this, you refresh your page first and then go to next page, when you return back it will be having the last refreshed state.
当您使用它时,您先刷新页面,然后转到下一页,当您返回时,它将处于最后一次刷新状态。
I have used it in a CAS login and gives me what I want. Hope it helps .......
我在 CAS 登录中使用了它,并给了我我想要的。希望能帮助到你 .......
details found from here
从这里找到的详细信息

