- History: back() method
- Syntax
- Parameters
- Return value
- Examples
- HTML
- JavaScript
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- How to get the previous URL in JavaScript?
- 9 Answers 9
- Window history.back()
- Note
- See Also:
- Syntax
- Parameters
- Return Value
- Browser Support
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- How to force reloading a page when using browser back button?
- How to force reloading a page when using browser back button?
- How to refresh page on back button click?
- History.back and reload the page
History: back() method
The History.back() method causes the browser to move back one page in the session history.
It has the same effect as calling history.go(-1) . If there is no previous page, this method call does nothing.
This method is asynchronous. Add a listener for the popstate event in order to determine when the navigation has completed.
Syntax
Parameters
Return value
Examples
The following short example causes a button on the page to navigate back one entry in the session history.
HTML
button id="go-back">Go back!button>
JavaScript
.getElementById("go-back").addEventListener("click", () => history.back(); >);
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Apr 7, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
How to get the previous URL in JavaScript?
Is there something like that? Or should I just store it in a cookie? I only need to know so I can do transitions from the previous URL to the current URL without anchors and all that.
9 Answers 9
in many cases will get you the URL of the last page the user visited, if they got to the current page by clicking a link (versus typing directly into the address bar, or I believe in some cases, by submitting a form?). Specified by DOM Level 2. More here.
window.history allows navigation, but not access to URLs in the session for security and privacy reasons. If more detailed URL history was available, then every site you visit could see all the other sites you’d been to.
If you’re dealing with state moving around your own site, then it’s possibly less fragile and certainly more useful to use one of the normal session management techniques: cookie data, URL params, or server side session info.
There’s also document.referrer, if you arrived at the current page via a link (but not, for example, by bookmark or typing in the address bar).
i ended up storing the previous url in cookies for the site, document.referrer doesn’t always work. $.cookie(«previousUrl», window.location.href,
If you want to go to the previous page without knowing the url, you could use the new History api.
history.back(); //Go to the previous page history.forward(); //Go to the next page in the stack history.go(index); //Where index could be 1, -1, 56, etc.
But you can’t manipulate the content of the history stack on browser that doesn’t support the HTML5 History API
For more information see the doc
Not necessarily, Mike — you can usually assume all the properties of window are available in the global context. window.history and history should usually be the same thing.
If you are writing a web app or single page application (SPA) where routing takes place in the app/browser rather than a round-trip to the server, you can do the following:
window.history.pushState(< prevUrl: window.location.href >, null, "/new/path/in/your/app")
Then, in your new route, you can do the following to retrieve the previous URL:
window.history.state.prevUrl // your previous url
Not able to find the prevURl? How to find that? I will be needing two three previous url from history. ?
document.referrer is not the same as the actual URL in all situations.
I have an application where I need to establish a frameset with 2 frames. One frame is known, the other is the page I am linking from. It would seem that document.referrer would be ideal because you would not have to pass the actual file name to the frameset document.
However, if you later change the bottom frame page and then use history.back() it does not load the original page into the bottom frame, instead it reloads document.referrer and as a result the frameset is gone and you are back to the original starting window.
Took me a little while to understand this. So in the history array, document.referrer is not only a URL, it is apparently the referrer window specification as well. At least, that is the best way I can understand it at this time.
Window history.back()
The history.back() method loads the previous URL (page) in the history list.
The history.back() method only works if a previous page exists.
Note
history.back() is the same as history.go(-1) .
history.back() is the same as clicking «Back» your browser.
See Also:
Syntax
Parameters
Return Value
Browser Support
history.back() is supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
How to force reloading a page when using browser back button?
Question: 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. When the page is reloaded from the client’s cache on back button of browser, the body’s onload event will fire again.
How to force reloading a page when using browser back button?
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.
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 can use pageshow event to handle situation when browser navigates to your page through history traversal:
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.
For more information check:
- Working with BFCache article on MDN
- WebKit Page Cache II – The unload Event by Brady Eidson
- pageshow event reference on MDN
- Ajax, back button and DOM updates question
- JavaScript — bfcache/pageshow event — event.persisted always set to false? question
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.
performance.navigation.type
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
if(performance.navigation.type == 2)
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.
These are detailed here: https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigation
Note Performance.navigation.type is now deprecated in favour of PerformanceNavigationTiming.type which returns ‘navigate’ / ‘reload’ / ‘back_forward’ / ‘prerender’: https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming/type
Since performance.navigation is now deprecated, you can try this:
var perfEntries = performance.getEntriesByType("navigation"); if (perfEntries[0].type === "back_forward")
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.
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, ‘./’);
so when you do use history.pushState(); make sure you use it properly.
Suggestion in most cases you will just need:
No window.history. and make sure url is defined.
Javascript — clear input fields on page refresh (Microsoft, document.getElementById (‘input_field’).value = »; This works fine in Firefox; when the page is refreshed, the value is emptied and the field is cleared. …
How to refresh page on back button click?
I use .htaccess to route all of my traffic to a single index.php file. The code below to directs traffic, but for some reason it doesn’t work with the back button. I don’t know what to do to get the back button working. I’ve tried a variety of things and googled quite a bit and none of it has worked so I’m hoping someone here can help!
So far I’ve tried and failed to use: window.onbeforeunload body onunload=»»
There has got to be a way to onunload=location.reload() or something! Somehow has to know the syntax!!
Try this. not tested. I hope it will work for you.
Make a new php file. You can use the back and forward buttons and the number/timestamp on the page always updates.
The onload event should be fired when the user hits the back button. Elements not created via JavaScript will retain their values. I suggest keeping a backup of the data used in dynamically created element within an INPUT TYPE=»hidden» set to display:none then onload using the value of the input to rebuild the dynamic elements to the way they were.
A more recent solution is using the The PerformanceNavigation interface:
if(!!window.performance && window.performance.navigation.type === 2)
Where the value 2 means «The page was accessed by navigating into the history».
View browser support here: http://caniuse.com/#search=Navigation%20Timing%20API
The hidden input solution wasn’t working for me in Safari. The solution below works, and came from here.
window.onpageshow = function(event) < if (event.persisted) < window.location.reload() >>;
I found two ways to handle this. Choose the best for your case. Solutions tested on firefox 53 and Safari 10.1
1. Detect if user is using the back/foreward button, then reload whole page
if (!!window.performance && window.performance.navigation.type === 2) < // value 2 means "The page was accessed by navigating into the history" console.log('Reloading'); window.location.reload(); // reload whole page >
2. reload whole page if page is cached
window.onpageshow = function (event) < if (event.persisted) < window.location.reload(); >>;
How to keep scroll position of page on refresh, User1451609391 posted Hello. I am working on mvc5 I have looked around on maintaining the scroll position of a page when i reload it. I cannot find …
History.back and reload the page
Is there a way to go back to the previous page and reload it ?
Write » Response.Cache.SetNoStore(); » in your Page_load event of page which you want to reload on back.
Use hidden field to a new value in the body’s onload event. When the page is reloaded from
the client’s cache on back button of browser, the body’s onload event
will fire again. Anytime when page load onload even gets fire. Check whether it has been reloaded from the server or from the
client, using the hidden field. If it has the new value, use
window.navigate(document.location.href) to reload the page from the server. You need to put body_Onload on body tag of the page.
function body_Onload() <
if(hidIsReload.value!=»initialvalue») <
window.navigate(document.location.href);
>else <
hidIsReload=»newvalue»
>
Is there a way to go back to the previous page and reload it ?
Add this to the page in page load
Response.Cache.SetCacheability( HttpCacheability .NoCache);
it will download a fresh page from server and not from cache each time you go back hence no need to realod
Different ways to disable caching of page and that’s one of them. Simple thing to do don’t let the page to be cached so that its downloaded from server each time
History.back and reload the page, Write » Response.Cache.SetNoStore (); » in your Page_load event of page which you want to reload on back. Use hidden field to a new value in the …