Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

[SugarCube] window.history.replaceState - safe to use?

I think this should work, but I'm definitely a bit out of my depth with this one. I have an auto-generated index page that lays out all of the most important passages in my piece. When she reaches the Index passages (it's the last one to be reached), I want to silently update the page's URL to add a query string so that, if she then bookmarks the page--as I will suggest she do!--that URL will be the one that is saved. That way, she will return to the index should she follow the bookmark. I have implemented a system to grab query strings from the URL and act on them, whether they are used to navigate to a new passage or set a variable, so e.g., we might update the bare story URL to this:
http://mystory.com/story.html?nav=Index
Now, it is possible (in modern browsers) to update the page URL without reloading the page by using window.history.replaceState(). But I am not sure whether it would be safe to do this in Sugarcube/Twine/Tiddlywiki due to the fact that the latter does its own history management.

If it is safe, to do that, I am also not sure what the best arguments are to supply to the replaceState method so that they comport with what Twine expects:
window.history.replaceState("object or string", "state title", "URL");
I do know what to supply for URL--I have to check the existing URL to see whether it's necessary to add the query string (it might already be there), or whether to format it as &nav=Index instead of ?nav=Index if there are other queries already present.

Thanks for any help!

Comments

  • Erik wrote:

    But I am not sure whether it would be safe to do this in Sugarcube/Twine/Tiddlywiki due to the fact that the latter does its own history management.


    That the headers have their own own history management is largely immaterial, that they store data in window.history by default is the problem.  So, the challenge is replacing the URL, while keeping the state data intact.

    That said, and without testing, you should be able to do something like this:

    window.history.replaceState(window.history.state, document.title, YOUR_URL_HERE);
    That should replace only the URL.  Well, it will replace everything, but the other two values will be what's already set for those parameters, so you'll really only be replacing the URL.
  • Thank you--that seems to work perfectly!
Sign In or Register to comment.