Can any one give a working example for history.replaceState? This is what w3.org says:
history . replaceState(data, title [, url ] )
history.pushState
pushes the current page state onto the history stack, and changes the URL in the address bar. So, when you go back, that state (the object you passed) are returned to you.
Currently, that is all it does. Any other page action, such as displaying the new page or changing the page title, must be done by you.
The W3C spec you link is just a draft, and browser may implement it differently. Firefox, for example, ignores the title
parameter completely.
Here is a simple example of pushState
that I use on my website.
(function($){
// Use AJAX to load the page, and change the title
function loadPage(sel, p){
$(sel).load(p + ' #content', function(){
document.title = $('#pageData').data('title');
});
}
// When a link is clicked, use AJAX to load that page
// but use pushState to change the URL bar
$(document).on('click', 'a', function(e){
e.preventDefault();
history.pushState({page: this.href}, '', this.href);
loadPage('#frontPage', this.href);
});
// This event is triggered when you visit a page in the history
// like when yu push the "back" button
$(window).on('popstate', function(e){
loadPage('#frontPage', location.pathname);
console.log(e.originalEvent.state);
});
}(jQuery));
I really wanted to respond to @Sev's answer.
Sev is right, there is a bug inside the window.history.replaceState
To fix this simply rewrite the constructor to set the title manually.
var replaceState_tmp = window.history.replaceState.constructor;
window.history.replaceState.constructor = function(obj, title, url){
var title_ = document.getElementsByTagName('title')[0];
if(title_ != undefined){
title_.innerHTML = title;
}else{
var title__ = document.createElement('title');
title__.innerHTML = title;
var head_ = document.getElementsByTagName('head')[0];
if(head_ != undefined){
head_.appendChild(title__);
}else{
var head__ = document.createElement('head');
document.documentElement.appendChild(head__);
head__.appendChild(title__);
}
}
replaceState_tmp(obj,title, url);
}