Remember history.replaceState method applied to solve a single-page application switching refresh the page problem

Well, before you know history api added a few new methods studied but did not how, today encountered a small problem, with history the perfect solution, very excited, recorded

First, referring to the next scene I encountered a problem:

There are two pages A, B

Submit information page A page B page when the page is the result

And A, B within the same page is a html file with js template for dynamic rendering,

Then when the results page dynamically rendered, will appear each time you refresh the page A, in fact, I want to show it on page B certainly do not want users to submit once again, but in most cases I actually do not want the user to go directly to submit information page, because if it is paid, it will cause secondary payments,

And also there is an error in logic, I'm A page refresh, you should let me in A page instead of asking the display page B? ? ? ?

So this is the time to show their talents replaceState time.


                var stateObject = { result: true }; //可以传递参数
                var title = "Wow Title";
                var newUrl = location.href;
                history.replaceState(stateObject, '', newUrl);
                console.info('history', history);

The middle of the title transfer empty, because most browsers have chosen to ignore it ==,
stateObject is to pass parameters

可以用 history.state直接获取到

Then this thing becomes easy, replacing the connection A page B page rendering when, in fact, this case is just a result parameter passed, then when the page is refreshed whenever it detects a result of this parameter is true that is displayed directly results page. And when the user clicks browser back button, it also will not return to the A page, avoid submitting again.

Perhaps vue react single-page application can also be achieved in this way, to remember a primer, and have time to try the next.

This example may be more abstract, there is time to complete the entire demo

Attach history api official website Description Address bar

https://developer.mozilla.org/zh-CN/docs/Web/API/History

Guess you like

Origin blog.51cto.com/13496570/2416791