djd97 djd97 - 6 months ago 78
Javascript Question

HTML history.pushState isn't working properly

I'm trying to figure out how to make pushState work so I'm testing with a simple HTML page with a single button in it as follows, but it doesn't change the url or seem to do anything.

<div id="test">
<button id="btn">Click Me</button>

history.pushState({}, '', 'newurl.html');


There is nothing wrong with that code.

I was able to reproduce the problem by trying to load the document directly from my local disk (via a file: URL). It gave this error message:

x.html:9 Uncaught SecurityError: Failed to execute 'pushState' on 'History': A history state object with URL 'file:///Users/myusername/tmp/fjdkfjkd/newurl.html' cannot be created in a document with origin 'null' and URL 'file:///Users/myusername/tmp/fjdkfjkd/x.html'.document.getElementById.onclick @ x.html:9

When I loaded the document from a web server (over HTTP), the problem went away.

You need to load your document from a web server.

There are lots of situations where things behave differently between file: and http: URLs (including scheme and root relative URLs, XMLHttpRequest, postmessage, and many others). Always do your testing over HTTP to avoid these problems.