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

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];
}

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);

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.

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

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();
}

}