Search code examples
javascriptbrowser-history

TypeError: 'replaceState' called on an object that does not implement interface History


I'm looking at this snippet of javascript code

if (history) {
    var action = settings.replaceState ? history.replaceState : history.pushState;
    if (action) {
        // next line throws the error
        action(null, null, window.location.pathname + window.location.search + '#' + hash);
    }
}

settings.replaceState == true

Microsoft's latest thing gives me this

Invalid calling object

In Chrome the same piece of code throws this

Uncaught TypeError: Illegal invocation

and I get this error in Firefox

TypeError: 'replaceState' called on an object that does not implement interface History.

When I debug the history looks as it should and there is a prototype containing this method in it.

Aside from the different error messages can anyone tell me what is going on here?


Solution

  • You lost the execution context of history by assigning the method to a variable. You need to set the execution context back to history by using call/bind

    action.call(history,null, null, 
                window.location.pathname + window.location.search + '#' + hash);