JavaScript does not refresh to implement browser's forward back function

Source: Internet
Author: User
Tags hash setinterval port number

Compared to the different pages of the jump, Ajax can be said to greatly improve the user's browsing experience, do not see the screen between the page is a very comfortable thing. But many of the earlier Ajax apps did not support the browser's forward retreat, which led users to go back to their original location whenever they browsed the site, and users were unable to switch browsing history through the browser's forward back button.

For the first problem, the solution is also easy, as long as the use of cookies or localstorage to record the status of the application, refresh the page read this state, and then send the corresponding AJAX request to change the page can be. But the second problem is very troublesome, first of all, the solution of modern browsers.

HTML5 Solutions

To understand how HTML5 can move forward backwards, you need to understand the history object and location object first.

History objects

History Object Properties

1.length: Returns the number of URLs in the browser history list, plus 1 for each page that the user accesses on the current tab. URL specific content is not visible because of privacy reasons.
2.state: Objects associated with the current URL can only be added or modified through pushstate and replacestate. We can use it to store information related to URLs.

History Object method

1.history.back ()

This method has no parameters and is triggered to return to the previous browsed page, which is equivalent to clicking the browser's Back button.

2.history.forward ()

This method has no parameters, and when triggered, it returns to the page that is browsed before the back, which is equivalent to clicking on the browser's forward button.

3.history.go (number)

This method accepts an integer variable parameter, history.go (-1) is equivalent to a back page, History.go (1) is equivalent to a forward page, History.go (0) refreshes the current page.

4.history.pushstate (state, title, URL)

The key to changing the URL and not refreshing the page is that it will change the current page's location.href and modify the current History.state object, and History.length will increase by 1 after execution. This method accepts three parameters,

1.state: The object associated with the current URL.
2.title: page title, but all browsers ignore it, to change the title or to use Document.title.
3.url: A URL with the same domain as the current page, Location.href will become this value.

5.history.replacestate (state, title, URL)

This method is the same, but it does not change the history.length and will only be modified when History.state and Location.href.

Note Pushstate and replacestate The third parameter is not cross-domain and does not trigger the browser's Popstate event and Onhashchange event (tested under Chrome33).

Location objects

In addition to clicking the Forward/Back button and the history event, you can also change the URL by location the method and modifying the location properties:

Properties of the Location object (read-write):

1.host: Domain name + port number
2.hostname: Domain Name
3.port: Port number
4.protocol: protocol
5.href: Full path
6.origin: protocol + domain name + port
7.hash: The URL (hash) at which the well number (#) begins
8.pathname: Document path + document name
9.search: (?) What's behind

You can change the location.href or Location.hash to achieve the goal of no refresh.

Ways to Location objects:

1.assign: Change the value of the URL and add the current URL to the history history.length will increase by 1. Location.assig (' # ' + x) changes the URL but does not refresh the page.
2.reload: Refresh the page.
3.replace: Change the value of the URL, but history.length unchanged. Use the method with assign.

Popstate Events

When the URL changes, such as when the user clicks the Forward/Back button, History.go (n) (n is not equal to 0), Location.hash = x (x is not equal to the current Location.hash) triggers this event. You can use it to listen for URLs to achieve a variety of functions.

The

code is as follows:


window.onpopstate = function () {


//do sth


    }

Onhashchange Events

Changing the hash value triggers the Popstate event, and triggering the Popstate event does not necessarily trigger the Onhashchange event. After testing:

1.hash change But location.pathname will trigger Onhashchange events, such as History.pushstate (",", ' #abc ');
2.hash changes with Location.pathname do not trigger, such as history.pushstate (",", ' a#abc ');

The writing of old browsers

Older browsers do not support Pushstate and replacestate, so the way to monitor URL changes via Popstate (which does not actually support this method) is not going to work. Then only by changing the content behind the url# to no refresh, but they do not support onhashchange, so the changes to the URL is indifferent (except the page will scroll to the location of the page ID). Then only the big strokes: polling, a setinterval to listen to the value of the URL. Like this:

The

code is as follows:


var prevhash = Window.location.hash;


var callback = function () {...}


Window.setinterval (function () {


if (Window.location.hash!= prevhash) {


Prevhash = Window.location.hash;


callback (Prevhash);


    }


}, 100);

Of course this is very very frustrated, if you do not consider clicking on the page with ID of a tag to change the situation of the hash, you can use the design mode to gracefully implement the listening URL. For example, the Classic observer pattern, which uses a class to implement the function of changing the hash, then all the classes (observers) that listen for URL changes subscribe to this (observed) class.

The

code is as follows:


//Change the URL class


function Urlchanger () {


var _this = this;


this.observers = [];


//Add observer


this.addobserver = function (obj) {...}


//Delete observer


this.deleteobserver = function (obj) {...}


//NOTIFY the Observer


this._notifyobservers = function () {


var length = _this.observers.length;


console.log (length)


for (var i = 0; i < length; i++) {


_this.observers[i].update ();


        }


    }


//Change URL


This.changeurl = function (hash) {


Window.location.hash = hash;


_this._notifyobservers ();


    }


}


//Listening class


function Oneofobservers () {


var _this = this;


this.update = function () {...}


}


//Implementation


var O1 = new Urlchanger ();


var O2 = new Oneofobservers ();


O1.addobserver (O2);


o1.changeurl (' fun/arg1/arg2/');


//o2 has do sth ...
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.