i




 
Thread Rating:
  • 0 Votes - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
HTML5 Session History and Navigation API
08-28-2011, 11:57 AM (This post was last modified: 08-28-2011 12:27 PM by haider.ali.)
Post: #1
HTML5 Session History and Navigation API
To detect if your browser support HTML5 Session History and Navigation API we use the following code

Code:
function isBrowserSupportHistory() {
            return !!(window.history && history.pushState);
        }
Push state
Now if we want to push the the new url into the stack we can do this by


Code:
var support = false;
function pushurl() {
            support = isBrowserSupportHistory();
            if(support ) {
                for( var i = 0; i < 10; i++ ) {
                    history.pushState(i, 'i is ' + i, '/' + i + '.html');
                }
            } else {
                       alert('browser not supported')
            }
        }

        window.onload = function() {
            pushurl();
        }

first argument in history.pushState method is state object it can be any JavaScript object, second argument is description and third is the URL of the page. I've used i as the state object because it's easy understand what is going into the history stack and act just like index to an array.

The above code will push 10 url in the history stack and if you press back button you will see the pages which you haven't visited but push method pushed it.


Remember it will not work in local file system you have to deploy it in some server or iis

PopState

when user presses back or forward button or history.go is called in JavaScript popstate event is fired below is the code to handle the pop state event in JavaScript.

Code:
window.onpopstate = HpopState;

you can write above code in the pushurl mehod after we check the history support.

Code:
function HpopState(event) {
            if(event.state != null) {
                //do your stuff here
            }


first we check that event object has state attribute , i
the event argument contain the state object which is the first argument in the push method.


ReplaceState

to update the current URL in the history stack we use following code

Code:
history.replaceState(0, 'the number 0', null);


here argument are as same as push object, here you can see we are passing null in 3rd argument so it will not replace the URL but state object and description is updated.


what it will do is replace the the top of stack with current info


and remember if we start pushing the url we dont have access to top of stack so it should come before pushing any url e.g

Code:
history.replaceState(0, 'the number 0', null);
history.pushState(1, 'the number 1', '1.html')



Quote


Possibly Related Threads...
Thread: Author Replies Views: Last Post
  using new html5 classlist api haider.ali 0 4,999 12-20-2011 07:21 AM
Last Post: haider.ali



User(s) browsing this thread: 1 Guest(s)