After checking a lot of information, it seems that ajax is used to partially refresh to another page, that is, there are two html files, and the window.onpopstate and history.pushState methods are used to save the history and roll back the page. I would like to ask how to implement the browser's back function if using ajax or generating data on the current page? Can you give a specific example?
ajax compatible with history
A major pain point of ajax is that it cannot support browser forward and backward operations. Therefore, early Gmail used iframe to simulate ajax forward and backward operations.
Nowadays, H5 is popular and pjax is very popular. Pajax is a technology combined with ajax+history.pushState. Using it, you can change the page content by going forward and back through the browser without refreshing.
Check the compatibility first.
It can be seen that IE8 and 9 cannot use H5 history. You need to use the shim HTML5 History API expansion for browsers not supporting pushState, replaceState.
pjax
pjax is easy to use and only requires the following three APIs:
history.pushState(obj, title, url) means adding a history entry to the end of the page history. At this time, history.length will be +1.
history.replaceState(obj, title, url) means replacing the current history item with a new history item. At this time, history.length remains unchanged.
window.onpopstate is only triggered when the browser moves forward and backward (history.go(1), history.back() and location.href="xxx" will all trigger), and can be obtained in history.state at this time The state just inserted is the obj object (other data types are also acceptable).
We noticed that when entering a page for the first time,
history.length
值为1,history.state
is empty. As follows:1) In order to get
history.state
every time in the onpopstate event callback, you need to automatically replace the current url after the page is loaded.2) Every time an ajax request is sent, after the request is completed, the following is called to advance the browser history.
3) When the browser moves forward and backward, the
popstate
event will be automatically triggered. At this time, we manually take outpopstate
事件会自动触发, 此时我们手动取出history.state
, build the parameters and resend the ajax request or directly use the state value to restore the page without refreshing. .popstate
事件触发时, 默认会传入PopStateEvent
Event object. This object has the following properties.If you don’t understand, please go to: Ajax and history compatibility for more detailed explanation