Cristien
Cristien

Reputation: 23

history.pushState will not work

Here is my JS. I am just running this code locally on my machine and I cannot get the URL to change. Is there anything wrong with this?

$(document).ready(function() {

     $('#content').load('content/index.html'); 

      $('ul#nav li a').click(function(e) {

        href = $(this).attr("href");

        $('#content').load('content/' + href + '.html');

        history.pushState('', 'New URL: '+href, href);

        e.preventDefault();
    });
});

Upvotes: 1

Views: 4189

Answers (1)

  1. Declare href locally, like const href = $(this).attr("href"); or var href = $(this).attr("href");

  2. Set the first argument of the history.pushState to an {} instead of a "",

  3. Check if $("ul#nav li a").attr("href") is a valid URI string: console.log($("ul#nav li a"), typeof $("ul#nav li a").attr("href") === "string");

+

Your problem

You've got a SecurityError when you've executed the code with resources on the local file system.

The reason why this happens

You're executing your code on the local file system(file:///). It makes SecurityErrors because of the Same-origin policy.

Same-origin policy for file: URIs

It seems there is no specification for this; implementation(browser)-defined. Chrome has the strongest policy for this. The second strongest is Firefox, the third is Opera.

The solution

You have to put them all to your web server and run it on the server, or, set allow-file-access-from-files flag option in Google Chrome, security.fileuri.strict_origin_policy setting for FireFox.

Upvotes: 3

Related Questions