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.
How to detect such action via 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!"
You should use a hidden input as a refresh indicator, with a value of "no":
Now using jQuery, you can check its value:
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.
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
Documentation including browser support is here: 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
The
2
indicates the page was accessed by navigating into the history. Other possibilities are-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.1:
The page was accessed by clicking the Reload button or via the Location.reload() method.255:
Any other wayThese are detailed here: https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigation
You can use
pageshow
event to handle situation when browser navigates to your page through history traversal: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.For more information check:
Since
performance.navigation
is now deprecated, you can try this:Use following meta tag in your html header file, This works for me.
Reload is easy. You should use:
And detecting back is :