preface
At noon today, when I got my lunch box, I was eating a piece of deep-sea cod dipped in tomato sauce. It was so delicious that I could hardly describe it. Suddenly the product rushed over and said: “We want to make a search function, the user in the search box to enter different search terms, the URL will also change, but the page can not be refreshed… To ensure that users can refresh the page can also locate the current search keywords “bar, bar, bar, bar after a lot of said:” this requirement is very simple, I don’t care how to achieve “, then off… And left me alone, with my deep-sea cod fillets already chilled…
The temptinghistory API
History_API
Adds and modifies entries in history
HTML5 introduces history.pushState() and history.replacestate () methods, which add and modify history entries, respectively. These methods are usually used in conjunction with window.onpopState.
usehistory.pushState()
You can changereferrer
, it is sent by the userXMLHttpRequest
Request inHTTP
Head use, changestate
After creating theXMLHttpRequest
The object’sreferrer
Will be changed. becausereferrer
Yes identity creationXMLHttpRequest
When the objectthis
Represented by thewindow
In the objectdocument
theURL
.
Example of the pushState() method
let stateObj = {
foo: "bar"}; history.pushState(stateObj,"page 2"."bar.html");
Copy the code
If the current browser address for http://mozilla.org, the above method will make your browser’s address bar display for http://mozilla.org/bar.html, but will not cause the browser to load bar. The HTML, and even does not check bar. HTML exists.
Suppose the user now visits http://google.com again and clicks the back button. At this point, the address bar will show http://mozilla.org/bar.html, history. A copy of the state includes stateObj. The page is now displayed as bar.html. And because the page has been reloaded, the popState event will not be emitted.
If we click back button again, the page URL will be http://mozilla.org/foo.html, document object document will trigger another popstate event, this time the event object state of the object is null. Here, too, the return does not change the content of the document, although the document may change its content when it receives the PopState event, its content remains the same as the previous presentation, and the page is not refreshed.
PushState () method
PushState () takes three arguments: a state object, a title (currently ignored), and (optionally) a URL. Let’s explain the three parameters in detail:
- State Object– State object
state
Is aJavaScript
Object, throughpushState ()
Create a new history entry. Whenever the user navigates to a new state,popstate
The event will be raised, and the event’sstate
Property contains a copy of the history entry state object. A state object can be anything that can be serialized. The reason is thatFirefox
To save the state object on the user’s disk for use when the user restarts the browser, we specified that the state object should be serialized after representation640k
The size limit of. If you givepushState()
Method passes a serialized value greater than640k
The method throws an exception. If you need more space, use itsessionStorage
As well aslocalStorage
. - The title (the title) —
Firefox
Ignore this parameter for now, but you may need it in the future. Passing an empty string here should be safe against future changes to this method. Or, you can jump for thestate
Pass a short title. - URL– This parameter defines a new history
URL
Record. Notice that the callpushState()
The browser will not load this immediatelyURL
, but this may be loaded later in some casesURL
, such as when the user reopens the browser. newURL
It does not have to be an absolute path. If the newURL
Is the relative path, then it will be taken as relative to the currentURL
To deal with.newURL
Must be related to the currentURL
Cognate, otherwisepushState()
An exception is thrown. This parameter is optional. The default value is currentURL
.
In a sense, calling pushState() is similar to setting window.location = “#foo”; both create and activate a new history on the current page. But pushState() has several advantages:
- The new
URL
Can be with the currentURL
Homologous arbitraryURL
. Instead, set only when changing the hashwindow.location
Talent is the samedocument
. - If you areDon’t want to change
URL
, don’t change. Instead, setwindow.location = "#foo"
; The current hash is not#foo
To create a new history entry. - You can associate any data with a new history entry. The hashing approach encodes all the relevant data into a short string.
- If the title is later used by the browser, the data is available (hashes are not).
Note that pushState() never triggers a hashchange event, even if the new URL is only hashed differently from the old ONE.
ReplaceState () method
The use of history.replacEstate () is very similar to history.pushState(), except that replaceState() modifies the current history entry rather than creating a new one. Note that this does not prevent it from creating a new history entry in the global browser history.
Usage scenarios
ReplaceState () is used in situations where you want to update the state object or the URL of the current history in response to user action.
Example replaceState() method
Assuming that http://mozilla.org/foo.html carried out the following JavaScript code:
let stateObj = {
foo: "bar"}; history.pushState(stateObj,"page 2"."bar.html");
Copy the code
The two lines above can be found in the “pushState() method example “section. Then, assuming that perform the following JavaScript: http://mozilla.org/bar.html
history.replaceState(stateObj, "page 3"."bar2.html");
Copy the code
This will result in the address bar shows that http://mozilla.org/bar2.html, but the browser will not go to loading bar2. HTML. There is no need to check the bar2 HTML exists.
Suppose the user now redirects to http://www.microsoft.com and clicks the back button. Here, the address bar will show http://mozilla.org/bar2.html. If users click the back button again, the address bar will show http://mozilla.org/foo.html, completely cleared the bar. The HTML.
popstate
The event
Use window. onpopState to listen for return events
Every time the active history item changes, the PopState event is passed to the Window object. If the active history item was created by pushState or changed by replaceState, the state property of the POPState event contains a copy of the current history state object.
For an example, see window.onpopState.
It’s a bit like the git stash command, and then you can pop it out with the git Stash pop command.
Get the current state
When the page loads, there may be a non-null state object. This can happen, for example, if the page (via pushState() or replaceState()) sets the state object and the user restarts the browser. So when the page reloads, the page receives an onload event, but no popState event. However, if you read the history.state property, you will get the same state object as if popState were triggered.
Instead of waiting for a popState event, you can read the state object for the current history entry by using the history.state property like this:
let currentState = history.state;
Copy the code
contrast
pushState |
replaceState |
---|---|
A new history is created and activated on the current page, and clicking the back button returns you to the previous URL | Will modify the current history, press the back button, will skip the modified URL |
Reference: History_API
Turns out, this demand is really simple, finally can happily continue to eat my deep sea cod fillet…