Js click to return to jump to the specified page implementation process _ javascript skills

Source: Internet
Author: User
Tags seamonkey
This article mainly introduces the implementation process of js clicking and returning to jump to the specified page. If you need this function, you can refer to this function before using it, the principle and problems are explained in detail this time (because of the compatibility problem with the html5 new API, we recommend that you use this method on the Mobile End ).

Function Description:

Create a tab in the browser and specify a URL. After the webpage is loaded, you are not allowed to click back in the normal process. Because there are no related history records on the current tab, no records can be returned.

At the customer's requirement, add a link (such as the homepage) to his history. In this case, click return on the newly opened page to go to the homepage, let users see the various functions of the system and promote the platform.

I. Key Points of knowledge

HTML5 introduces the history. pushState () method and the history. replaceState () method, which allow you to add and modify history entries one by one. These methods work together with the window. onpopstate event.

Case:
HypothesisHttp://mozilla.org/foo.htmlThe following JavaScript code will be executed:

The Code is as follows:

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


This will display the address bar of the browserHttp://mozilla.org/bar.html, But the bar.html page does not exist.

Assume that the user hasHttp://google.comAnd then click the back button. The address bar will displayHttp://mozilla.org/bar.htmlAnd the page will trigger the popstate event. The state object in this event contains a copy of stateObj. This page looks like foo.html, although the page content may be modified in the popstate event.

If we click the back button again, the URL will be changed back.Http://mozilla.org/foo.htmlThe document will trigger another popstate event. This time the State object is null. Rollback does not change the document content.

PushState () method
PushState () has three parameters: a State object, a title (ignored now), and an optional URL address. The following describes the details of these three parameters:

State object)-A JavaScript Object associated with the new history entries created using the pushState () method. The popstate event is triggered whenever you navigate to the newly created state, and the state attribute of the event object contains a copy of the state object of the historical record entry.

Any serializable object can be regarded as a State object. Because the FireFox browser will save the status objects to the user's hard disk, so that they can be restored after the user restarts the browser, We forcibly limit the size of the Status objects to 640 k. If you pass a status object that exceeds the limit to the pushState () method, this method throws an exception. If you need to store large amounts of data, sessionStorage or localStorage is recommended.

Title)-This parameter is currently ignored in FireFox, although it may be used later. Considering that this method may be modified in the future, it is safer to pass an empty string. Alternatively, you can enter a brief title to indicate the status to enter.

URL)-The address of the new record entry. The browser does not load the address after calling the pushState () method, but may try to load it later, for example, 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 input URL and the current URL should be the same source; otherwise, pushState () an exception is thrown. This parameter is optional. If this parameter is not specified, it is the current URL of the document.

Note: In Gecko 2.0 (Firefox 4/Thunderbird 3.3/SeaMonkey 2.1) to Gecko 5.0 (Firefox 5.0/Thunderbird 5.0/SeaMonkey 2.2), the input object is serialized using JSON. Starting from Gecko 6.0 (Firefox 6.0/Thunderbird 6.0/SeaMonkey 2.3), objects are serialized using a structured copy algorithm. This allows more types of objects to be passed in safely.
In a sense, calling pushState () is a bit similar to setting window. location = '# foo'. They all create and activate new history entries in the current document. But pushState () has its own advantages:

1. The new URL can be any same-source URL. In contrast, when using the window. location Method, only modification to hash can be ensured to stay in the same document.

2. Determine whether to modify the URL based on your needs. On the contrary, when window. location = '# foo' is set, a new history record is created only when the current hash value is not foo.

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

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

Popstate event
The popstate event is triggered whenever the active history changes. If the activated history entries are created by pushState or are affected by the replaceState method, the status attribute of the popstate event contains a copy of the status object of the history.

ReplaceState () method
The history. replaceState () operation is similar to history. pushState (). The difference is that the replaceState () method modifies the current historical record entries rather than creating new ones.

The replaceState () method is especially suitable when you want to update the status object or URL of the current history record in response to some user operations.

II. Implementation ideas
1. Use the popstate event to listen and click to return the event.

2. When an event is triggered, determine whether the history of the current page has a page to return.

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

1). the specified jump page.

2) Empty record. (Keep the current page unchanged)

Iii. Implementation Method

// If no page is returned, the home page 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) // console. log (history. state )}

Determines the number of records in the current history. When a page is loaded, the browser automatically pushes a record. Therefore, determine whether the length is less than 2.

The inserted state object is used to obtain the corresponding url link.
Note:
In the first pushState, I put the jump url into the state object to facilitate the jump operation. The second parameter has no practical significance, because the current browser basically does not apply this parameter.
The third parameter will replace the link in the current address bar, but the page will not jump. (I made a mistake and set the third parameter as the homepage link. As a result, the address bar is changed to the homepage link, so that all links on the current page are redirected Based on the homepage, as a result, all links on the page are redirected incorrectly .)

  setTimeout(function () {      pushHistory()      window.addEventListener("popstate", function (e) {        lll("popstate"+window.history.state)        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. The latency is 300 milliseconds to delay the operation and prevent conflicts with system pop events.
To determine whether a state object exists in history, the if statement performs page Jump operations based on this because only records that meet our requirements have the state object we added.
In this way, we can achieve the desired effect.
4. Write at the end
Disadvantages:
1. Obviously, as mentioned at the beginning. Only applicable to browsers that support html5.
2. Because two records are inserted, a return similar to this kind of mobile terminal needs to be clicked twice to return to the page and return to the chat window. The user experience is poor.

Summary:
This method can be optimized and improved, but it is not enough to perfect my current strength.

I hope that my friends who have read this article can get some inspiration or have better implementation methods.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.