JS Click to return to the specified page to achieve the process _javascript skills

Source: Internet
Author: User
Tags seamonkey

This function has a simple before, this detailed explanation of the principle and existing problems (due to the use of HTML5 new API so there are compatibility issues, recommended mobile end to use this method).

Function Description:

Create a new tab in the browser and specify a URL, the page after loading, the normal process is not allowed to click Back. There is no record to return because the relevant history of the current tab page is not available.

In response to customer requirements, need in this case, to his history to add a link (such as the home page), so in the newly opened pages, click Return can jump to the home page, let users see the system's various functions, promote the platform.

I. Points of knowledge

HTML5 introduces the History.pushstate () method and the History.replacestate () method, which allows you to add and modify the history entries one after the other. These methods can work together with window.onpopstate events.

Case:
Suppose http://mozilla.org/foo.html will execute the following JavaScript code:

Copy Code code as follows:
var stateobj = {foo: ' Bar '}; History.pushstate (Stateobj, "Page 2", "bar.html");

This will allow the browser's address bar to display http://mozilla.org/bar.html, but will not load the bar.html page nor check if bar.html exists.

Let's say the user navigates to the http://google.comand then clicks the Back button, and the Address bar will show http://mozilla.org/bar.html, And the page triggers a popstate event in which the state object contains a copy of the stateobj. The page looks like foo.html, although the page content may have been modified in the Popstate event.

If we click the Back button again, the URL will change back to the http://mozilla.org/foo.html document will trigger another Popstate event, this time the state object is null. Rollback also does not change the contents of the document.

Pushstate () method
Pushstate () has three parameters: a state object, a caption (which is now ignored), an optional URL address. Here's a separate look at the details of these three parameters:

state Object -a JavaScript object that is associated with a new history entry created with the Pushstate () method. Whenever a user navigates to a newly created state, the Popstate event is triggered, and the state property of the event object contains a copy of the status object for the history entry.

Any serializable object can be treated as a state object. Because the Firefox browser saves the status object to the user's hard disk so that they can be restored after the user restarts the browser, we force the size of the state object to be 640k. If you pass a state object that exceeds that limit to the Pushstate () method, the method throws an exception. If you need to store large data, it is recommended to use Sessionstorage or localstorage.

title -firefox Browser currently ignores this parameter, although it may be used later. Given that the method may be modified in the future, it is safer to pass an empty string. Alternatively, you can pass in a short title indicating the state you are going to enter.

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, such as when the user restarts the browser. The new URL is not necessarily an absolute path, and if it is a relative path, it will be based on the current URL, and the incoming URL should be homologous to the current URL, otherwise pushstate () throws an exception. The parameter is optional, or the current URL of the document if not specified.

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 incoming objects are serialized using JSON. Starting with the Gecko 6.0 (Firefox 6.0/thunderbird 6.0/seamonkey 2.3), objects are serialized using a structured copy algorithm. This will allow more types of objects to be safely passed in.
In a sense, calling Pushstate () is somewhat similar to setting the window.location= ' #foo ', which creates and activates new history entries within the current document. But Pushstate () has its own advantages:

1, the new URL can be any homologous URL, in contrast, when using the Window.location method, only the hash can be modified only to ensure that stay in the same document.

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

3, you can add abstract data to the new history entry. If you use a hash based approach, you can only turn the relevant data into a very short string.

Note that the Pushstate () method never triggers the Hashchange event, even if the new address only changes the hash.

Popstate Events
The Popstate event is triggered whenever the history of the activation changes. If the active history entry is created by pushstate or affected by the Replacestate method, the State property of the Popstate event will contain a copy of the state object of the history record.

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 entry.

Using the Replacestate () method is especially appropriate when you want to update the status object or URL of the current history entry in response to some user action.

Second, the realization of ideas
1. Using the Popstate event, listen for the Click Return event.

2. When triggering an event, determine whether the current page's history has a page that can be returned.

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

1), the specified jump page.

2), the blank record. (Make the current page not change)

Iii. Methods of implementation

 Back to the page before returning no 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) 
}

To determine the number of records in the current history, the browser will automatically push into a record as the page loads. So to determine whether the length is less than 2.

The state object is plugged in to get the corresponding URL link.
Note the point:
First pushstate I put the jump URL into the state object to facilitate the jump operation. The second argument has no practical meaning because the current browser basically does not apply to this parameter.
The third parameter replaces the link in the current address bar, but the page does not jump. (I made a mistake before, set the third parameter as the first page link, resulting in the address bar changes to the home page link, so that the current page of the link to the homepage for the basis of the jump, resulting in all the links to the page is wrong.) )

  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 placed in the ready event of the page and is delayed by 300 milliseconds in order to delay the operation and prevent conflicts with system pop events.
If statement to determine whether there is a state object history, because only the records that meet our requirements will have the state object we added so that the page can be jump operation based on this point.
This will enable us to achieve the desired effect.
four, write in the last
Disadvantages:
1. Obviously, as mentioned at the beginning. Only suitable for browsers that support HTML5.
2. As a result of inserting two records, so similar to the micro-letter of the mobile end of the return, the need to click two times to return, in order to launch the page, back to the micro-mail Chat window, the user experience is not good.

Summarize:
This method must also be optimized and perfect, but at present my strength is insufficient, still not enough to perfect to the degree of perfection.

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

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.