Setting variable values in URL string

Hi there!

I’m trying to figure out if it’s possible to set variables in a twine story as a string in the opening URL. So, if someone opens the story from an email, they could have ?name=thisperson in it, to give some customisation from the get-go.

I’m new to twine, but couldn’t see anything on here suggesting that it was/ wasn’t possible. Any pointers would be greatly appreciated!

Yes, you can do that, though the exact method depends on what Story Format you’re using (e.g. Harlowe, SugarCube, etc.). If you set the optional tag on your post to your Story Format, that makes it easier for us to provide you the correct support.

If you’re using SugarCube, you could put this in your JavaScript section:

setup.name = (new URLSearchParams(document.location.search)).get("name");

That stores the value in the URL after ?name= on the SugarCube “setup” object, so you can access that value elsewhere in your code. See the Document.location property and the HTMLHyperlinkElementUtils.search property for details on how that works.

Then you’d put this in your StoryInit passage:

<<if (typeof setup.name === "string") || (setup.name instanceof String)>>
	<<set $name = setup.name>>
<<else>>
	<<set $name = "">>
<</if>>

And that would set $name to the .name property on the setup object which we set earlier in the JavaScript section, or if a name isn’t in the URL, it sets $name to an empty string.

Hope that helps! :slight_smile:

It should be noted that the URLSearchParams interface is not supported by any version of Internet Explorer.

If you need to support Internet Explorer (which is a good idea, because a surprisingly large number of people are still using it) you can use this URLSearchParams Polyfill to provide the same functionality within the later versions of that browser.