history.replaceState() example?

Serjas picture Serjas · Oct 11, 2012 · Viewed 211.4k times · Source

Can any one give a working example for history.replaceState? This is what w3.org says:

history . replaceState(data, title [, url ] )

Updates the current entry in the session history to have the given data, title, and, if provided and not null, URL.

Update:

This works perfectly:

history.replaceState( {} , 'foo', '/foo' );

Url is changing, but title is not changing. Is that a bug or am I missing something? Tested on latest Chrome.

Answer

Sev picture Sev · Oct 15, 2012

Indeed this is a bug, although intentional for 2 years now. The problem lies with some unclear specs and the complexity when document.title and back/forward are involved.

See bug reference on Webkit and Mozilla. Also Opera on the introduction of History API said it wasn't using the title parameter and probably still doesn't.

Currently the 2nd argument of pushState and replaceState — the title of the history entry — isn't used in Opera's implementation, but may be one day.

Potential solution

The only way I see is to alter the title element and use pushState instead:

document.getElementsByTagName('title')[0].innerHTML = 'bar';
window.history.pushState( {} , 'bar', '/bar' );