javascriptjquerytransition

How to change the url with history.pushState to create a page transition with jQuery Ajax?


I am trying to achieve a seamless page transition using window.history.pushState(), to change the url in the address bar. I followed the this tutorial, but pushState throws the following error: Uncaught DOMException: Failed to execute 'pushState' on 'History': A history state object with URL [link] cannot be created in a document with origin 'null' and URL

Does anyone know how to fix this. The thing I trying to achieve is, to get the href of the button that is clicked and change the url for example from: http://www.example.com/index.html to http://www.example.com/about.html.

$('.button').on('click', function(e) {
        e.preventDefault();

        var href = $(this).attr('href');
        window.history.pushState(null, null, href); 

        $.ajax({
            url: href,
            success: function(data) {
                // Do animation and change content
            }
        });
    });

Solution

  • You would not get that error message if you were trying to change the URL from http://www.example.com/index.html.

    A null origin is one on a page with a URL starting file:.

    You need to run the JS in a page with an origin which isn't null. i.e. on a web server with an HTTP(S) URL.