3

I am trying to push a state to the browser history, when clicking the text in the following div element:

<!DOCTYPE html>
<head>
</head>
<body>
<div onclick="onNavigate('/tester')">link</div>
<script>const onNavigate = path => history.pushState("","", window.location.pathname + path)</script>
</body>
</html>

I get an

Uncaught DOMException error: Failed to execute 'pushState' on 'History': A history state object with URL 'Failed to execute 'pushState' on 'History': A history state object with URL 'file://[path-to-file]/index.html/tester' cannot be created in a document with origin 'null' and URL 'file://[path-to-file]/index.html'.' cannot be created in a document with origin 'null' and URL 'file://[path-to-file]/index.html'.

There are plenty similar posts related to pushState() and replaceState() - like this one History pushState throws Uncaught DOMException but none of them provide a working solution. I have also tried with location.href instead of location.pathname without success. What's wrong?

aknott
  • 195
  • 3
  • 11
  • Have you tried the code with an URL starting with http or https? Could be a problem with file. –  May 20 '21 at 22:46
  • nope - and I would really like to have this working both locally without backend. Bonus if it works also on a webserver – aknott May 20 '21 at 22:49
  • 1
    Your code works for me: https://jsfiddle.net/5gkf4x1z/ It's perhaps not allowed for security reasons with `file://` –  May 20 '21 at 22:49
  • Is this Firefox your using, as the origin of `file://` is null in Firefox,. Have you tried in Chrome.? – Keith May 20 '21 at 22:50
  • tried in Chrome (Version 90.0.4430.212) and Safari (the error message is slightly different in Safari - but same problem) – aknott May 20 '21 at 22:53
  • _"I would really like to have this working both locally"_ Then create a local server, as a developer, this will help you tons. There are many tools and many ways to do it – blex May 20 '21 at 22:53
  • @blex I need it to work without server. I do have a server test environment, but no-go in this case – aknott May 20 '21 at 22:55
  • 1
    That's not possible for security reasons: https://stackoverflow.com/questions/39814218/history-pushstate-will-not-work –  May 20 '21 at 22:58
  • 1
    If you don't want a server then you can use something like -> https://www.electronjs.org/ this is what VS Code uses, it's basically a browser attached to a NodeJS backend. I assume with this you can then alter origin security settings to allow pushState on `file://` urls. – Keith May 20 '21 at 23:02
  • That answers it. Thanks @jabaa – aknott May 20 '21 at 23:02

0 Answers0