简体   繁体   中英

How to trap the back button and refresh the page using ajax

I have a web page which updates progressivly therefore I need the windows "back" button to call a function to refresh the data and not go back a page. I have the first part working I trap the "back" button with

window.onbeforeunload = confirmExit();

and confirmExit()

function confirmExit() {
    switch (page) {
        case 2:
            countries();
            break;
         case 3:
            counties(page3id)
            break;
        case 4:
            cities(page4id)
            break;
    }
}

Which all works well but after the page is refreshed the back button default action kicks in and it loads the previous page. I have tried returning true and false. I would appreciate any help, thank you.

you need to add virtual sites to the browsers history. this way the back button will not lead to another website.

use history.pushState() to add virtual sites.

Suppose http://mozilla.org/foo.html executes the following JavaScript:

 var stateObj = { foo: "bar" }; history.pushState(stateObj, "page 2", "bar.html");

This will cause the URL bar to display http://mozilla.org/bar.html , but won't cause the browser to load bar.html or even check that bar.html exists.

Suppose now that the user now navigates to http://google.com , then clicks back. At this point, the URL bar will display http://mozilla.org/bar.html , and the page will get a popstate event whose state object contains a copy of stateObj. The page itself will look like foo.html, although the page might modify its contents during the popstate event.

If we click back again, the URL will change to http://mozilla.org/foo.html , and the document will get another popstate event, this time with a null state object. Here too, going back doesn't change the document's contents from what they were in the previous step, although the document might update its contents manually upon receiving the popstate event.

from MDN: Manipulating the browser history

the user can now press the back button the number of times you added virtual sites. to detect the back button press use window.onpopstate

The popstate event

A popstate event is dispatched to the window every time the active history entry changes. If the history entry being activated was created by a call to pushState or affected by a call to replaceState, the popstate event's state property contains a copy of the history entry's state object.

from MDN: Manipulating the browser history

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM