How can I detect that the browser back button has been pressed in a single page app?

时间:2016-04-04 16:49:48

标签: javascript jquery

On a certain page in my app, I have a popup guide that walks the user through several steps. When the user clicks the popup next button it advances, sometimes going to a new page (but not always). My problem is that when the user clicks the browser back button, the popup does not close and causes issues if the user tries to advance again. What i'd like to do is just close the popup if the user hits the browser back button. I'd assumed this would be an easy problem, but I can't figure out a solution.

Since this is a SPA, 'onbeforeunload' and 'onunload' don't fire. The way the app is setup, 'onpopstate' also doesn't fire. 'hashchange' fires, but it also fires sometimes when the user clicks the next button on the popup, and I don't see a way to differentiate between that hashchange and hashchange when the user clicks back.

Is there some other event I can check for? I just want to run a function to close my popup (and do cleanup) when the user clicks the back button.

1 个答案:

答案 0 :(得分:0)

The following assumes you do not use the history API:

Often times I have seen use of # (the anchor tag) in the URL. This will allow for navigation throughout a single page without refreshing the page. As the user progresses in the workflow. For example,

window.location.href = "http://stackoverflow.com/questions/36408418/how-can-i-detect-that-the-browser-back-button-has-been-pressed-in-a-single-page" + "#test"

will not refresh the page. When the back button is pressed, the following statement will evaluate to be true:

(window.location.href == "http://stackoverflow.com/questions/36408418/how-can-i-detect-that-the-browser-back-button-has-been-pressed-in-a-single-page")