- Home /
How to read URL parameters from Unity WebGL Build
I am building a browser based game targeting WebGL platform.
Once I build my game into WebGL, I am getting an index.html file and gamename.js file (Ignoring other generated files as I assume they might be relevant here).
Once I host the file, I will need to read the URL parameters which will be passed while I call the URL of my game.
The parameter can be something like an API key for instance, which will be used to connect the game to my back-end system.
So I need to know how can I access and use those parameters inside my game.
Any information on the same is welcomed. Thanks in advance
Answer by Landern · Dec 14, 2016 at 04:13 PM
You will want to read the manual when it comes to script interaction from WebGL platform builds, after that you will want to use javascript. In javascript the window.location.search object will contain what you're looking for(using substring(1) to pull the get parameters form the uri). You will want to split on the ampersand(&) and parse the key/value pairs. If you're sending in the header(POST) then the code will be different, but that should be enough to start with.
Thanks @Landern, it helped me jump into the problem and find a way. Cheers
Answer by Bunny83 · Jul 01, 2018 at 11:23 PM
Note, there's an update at the bottom of this answer
I've created this URLParameters singleton several years ago. Here's a WebGL example of a Mandelbrot renderer where i used this script to parse the hash parameters which get automatically adjusted when you change the settings.
This script doesn't need to be attached to a gameobject manually. Just register a callback like this in Start:
URLParameters.Instance.RegisterOnDone((url)=> {
Debug.Log("search parameters: " + url.Search);
Debug.Log("hash parameters: " + url.Hash);
});
This will automatically create an instance of the singleton which will send a javascript request to the browser which in turn will call a callback in that script which will trigger our callback. It also parses the search field as well as the hash / fragment into key-value-pairs in dictionaries. So you can do this in your callback:
string p = url.SearchParameters["myParameter"];
When you have an URL like this:
"https://my.domain.name/myPath.html?myParameter=Hello%20World"
"p" will contain "Hello World"
edit
Update
Since Unity is about to deprecate the ExternalEval API the original URLParameters may no longer work in the future. I've made a newer version of the URLParameters script which uses an embedded jslib file which should be auto-extracted into the plugins folder of your project on import.
Note that the new version works a bit different. Since we no longer have to use callbacks we can directly call those javascript extensions from C#. The script provides static properties which directly invoke a javascript method which immediately returns the current value from the JS world. The script doesn't need to be attached to anything anymore. However you can still attach it to an object in your scene to provide test data for in-editor testing.
The new class comes with a couple of static properties to directly read the different parts of the current location in the browser:
Protocol
Hostname
Port
Pathname
Search
Hash
And those 3 mixed properties Host, Origin and Href. For more information read the comments in the file.
Additionally there's two methods which split the search/query or the hash/fragment string into a dictionary for easy access. There are also two extension methods for a Dictionary<string,string>
(GetDouble, GetInt) which makes it very easy to directly parse numbers from such parameters
double d = URLParameters.GetSearchParameters().GetDouble("keyName", 42d);
Nice, but the method it uses: Application.ExternalEval has became obsolete.
Note that i've posted an update since the "old" way (using ExternalEval) may no longer work in the future as Unity has deprecated this API. I've linked a newer version that is using an embedded JSLib. Though the new version works a bit different and is even simpler on the C# side. (also i've fixed my example link).
This works perfectly! Thank you so much for your work to help the community.
Hi @Bunny83, this is perfect and working really fine. Can you give some examples to retrieve strings with your class in unity please? my url provides a param call site, such as site=playground. So I need to get that parameter too. Would anyone here can help with this? Thanks
As I said in my answer if you have a search parameter you can use GetSearchParameters() which returns a dictionary with the whole search string being parsed into name=value pairs.
So you can do:
var parameters = URLParameters.GetSearchParameters();
string site;
if (parameters.TryGetValue("site", out site))
{
// use "site" here
}
else
{
// no parameter with name "site" found
}
If you want to use a default value in case no site parameter was passed you can simply use
var parameters = URLParameters.GetSearchParameters();
string site;
if (!parameters.TryGetValue("site", out site))
{
// set default value here
site = "default site";
}
// use "site" here
hi @Bunny83 That's works perfectly. Thanks for sharing your knowledge with us. Best regards...
I am unable to get this to work can you please help me?
it prints 42 only everytime.
It doesn't return the string which i want it to return from the URL:(
Please, ask a seperate question if you have an issue. Also in your question you have to add more details what exactly you're doing and also which version of the script you're using. Also do you actually test this in an actual WebGL build? There are countless of open questions in regard to your specific issue that can not be answered in a comment here. That's why we have Questions and Answers. So if you have a question, please, post a seperate question. Feel free to add a cross link to this question. However don't forget to actually provide more details about your setup and your actual issue
Answer by tomekkie2 · Dec 14, 2016 at 04:27 PM
You can pass parameters in the index file url and retrieve them in your app like below:
int pm = Application.absoluteURL.IndexOf("?");
if (pm != -1)
{
sceneName = Application.absoluteURL.Split("?"[0])[1];
}
Like in the example here: http://virtualplayground.d2.pl/WebGL/st15/?4x3_cederroth
Answer by malviyanpawan · Aug 23, 2021 at 11:00 AM
I also facing the same issue for that i make a plugin and it works for me.
I've extended the .jslib a little bit to include another method that can extract query parameters from the URL (save this as GetURL.jslib in /Assets/Plugins/WebGL ):
mergeInto(LibraryManager.library, {
GetURLFromQueryStr: function () {
var returnStr = window.top.location.href;
var bufferSize = lengthBytesUTF8(returnStr) + 1
var buffer = _malloc(bufferSize);
stringToUTF8(returnStr, buffer, bufferSize);
return buffer;
}
});
To call the method, in C# I've created the following URLReader class/Component:
public class FetchURlQueryStr : MonoBehaviour { [DllImport("__Internal")] private static extern string GetURLFromQueryStr();
private void Start()
{
Debug.Log("App is running on the url>>>> " + ReadURLFromQueryStr());
}
public string ReadURLFromQueryStr()
{
return GetURLFromQueryStr();
}
}