js Click back to jump to the specified page implementation process

  • 2021-02-17 06:10:41
  • OfStack

This function has been briefly introduced before. This time, the principle and existing problems will be explained in detail (since it is the new API using html5, there are compatibility problems, so it is recommended to use this method on mobile terminals).

Function Description:

Create a new TAB page in the browser and specify a URL. After the page is loaded, it is not allowed to click back under the normal process. Because there is no history associated with the current TAB, there is no record to return.

At the request of the customer, it is necessary to add a link (such as home page) to his history record in this case, so that on the newly opened page, click back to jump to the home page, so that users can see the various functions of the system and promote the platform.

1. Knowledge points

HTML5 introduces the methods history.pushState () and history.replaceState (), which allow you to add and modify history entries item by item. These methods work in conjunction with the window.onpopstate event 1.

Case study:

Suppose http: / / mozilla org/foo html will perform the following JavaScript code:

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

This will allow the browser's address bar display http: / / mozilla org/bar html, but not loaded bar. html page won't check bar. html exists.

Assume that now the user navigation http: / / google com, and then click the back button, at this point, the address bar will show http: / / mozilla org/bar html, and page will trigger popstate events, the state of the event object (state object) contains stateObj 1 copy. The page looks like foo.html, although the content of the page may have been modified during the popstate event.

If we click the back button, once again URL will change back http: / / mozilla org/foo html document will trigger another 1 popstate event, state of the object for null. Rollback also does not change the content of the document.

pushState () method
pushState() takes three arguments: a status object, a title (which will be ignored for now), and an optional URL address. Let's look at the details of these three parameters separately:

Status object (state object) - An JavaScript object associated with a new history entry created with the pushState() method. The popstate event is triggered whenever the user navigates to the newly created state, and the state property of the event object contains a copy of the state object for the history entry.

Any serializable object can be treated as a state object. Because the ES85en browser saves the state objects to the user's hard drive so that they can be restored after the user restarts the browser, we force the size of the state objects to be 640ES86en. If you pass a status object to the pushState() method that exceeds this limit, the method will throw an exception. If you need to store large amounts of data, it is recommended to use sessionStorage or localStorage.

Title (title) - The FireFox browser ignores this parameter for now, although it may be used later. Given that this method may be modified in the future, it is safe to pass an empty string. Alternatively, you can pass in a short heading indicating the state to be entered.

Address (URL) - The address of the new history entry. The browser does not load the address after calling the pushState() method, but after that, it may attempt to load it, for example if the user restarts the browser. The new URL is not necessarily an absolute path; If it is a relative path, it will be based on the current URL; The passed URL should be cognate with the current URL; otherwise, pushState() throws an exception. This parameter is optional; If not specified, the document is currently URL.

Note: In Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) through Gecko 5.0 (Firefox 5.0 / Thunderbird 5.0 / SeaMonkey 2.2), incoming objects are serialized using JSON. As of Gecko 6.0 (Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3), objects are serialized using the structured copy algorithm. This will allow more types of objects to be passed in safely.
In a sense, calling pushState() is a bit like setting window.location ='#foo', both of which create and activate new history entries within the current document. But pushState() has its own advantages:

1. The new URL can be any URL with the same origin. In contrast, when using the window.location method, only modifying hash can ensure that it stays in the same document.

2, according to personal needs to decide whether to modify URL. Instead, set window.location='#foo' to create a new history only if the current hash value is not foo.

3. You can add abstract data to new history entries. With the hash-based approach, you can only transcode the relevant data into a very short string.

Note that the pushState() method never triggers an hashchange event, even if the new address only changes hash.

popstate event

The popstate event is fired whenever the active history changes. If the history entry being activated is created by pushState or is affected by replaceState methods, the state property of the popstate event will contain a copy of the history's state object.

replaceState () method

The history.replaceState () operation is similar to history.pushState (), except that the replaceState() method modifies the current history entry rather than creating a new one.

The replaceState() method is especially useful when you want to update the current history entry's state object or URL in response to some user action.

2. Implement ideas

1. Using popstate events, listen for click return events.

2. When triggering an event, determine whether the history of the current page has pages that can be returned.

3. If no page can be returned, insert two records:

1) The specified jump page.

2), empty record. (Leave the current page unchanged)

3. Implementation method

 // Return to the home page if there is no page before 
 function pushHistory() {
 if (history.length < 2) {
 var state = {
  title: "index",
  url: getHttpPrefix + "index.html"
 window.history.pushState(state, "index", location.href);
 state = {
  title: "index",
  url: ""
 window.history.pushState(state, "index", "");
 //lll("history.state" + history.state)

When the page is loaded, the browser will automatically enter 1 record in push. So we want to know if the length is less than 2.

The state object is inserted to get the corresponding url link.


The first pushState I put the jump url into the state object for easy jump operation. The second parameter is of no use because it is rarely used in current browsers.
The third parameter replaces the link in the current address bar, but the page does not jump. (I made a mistake before, setting the third parameter as Home Page Link, which caused the address bar to be changed to Home Page Link, so that all the links on the current page jump based on the home page, causing all the links on the page to jump wrong.)

 setTimeout(function () {
 window.addEventListener("popstate", function (e) {
 if (window.history.state != null && window.history.state.url != "") {
  location.href = window.history.state.url
 }, 300);

This code is executed in the ready event of the page, with a delay of 300 milliseconds in order to delay the operation and prevent it from colliding with the system pop event.
In order to determine whether there is an state object in history, only the records that meet our requirements will have the state object added, so we can jump the page according to this.
That will give us the effect we want.

4. Write it at the end


1. Obviously, as mentioned at the beginning. It is only suitable for browsers that support html5.

2. Because two records are inserted, the return of mobile terminal like WeChat needs to click twice to return before launching the page and returning to thWeChatB1 chat window, which has a poor user experience.


This method can still be optimized and improved, but my current strength is not enough to perfect the degree.

Hope to see this article friends can get some inspiration, or there is a better way to achieve.

Related articles: