When you are building a game, app, or experience using WebGL in Unity, there are chances that you may want to redirect the user to a different page, depending on the flow of your site.

When you are working to publish your app in other platforms than WebGL, or using old versions of Unity, you can just call Application.OpenUrl and get there.

This changed lately because 99% of the people (that’s a lot) wanted to open a new tab, so according to Unity’s documentation:

WebGL: From version 2019.4.25f1, 2020.3.5f1, 2021.1.2f1, and 2021.2.0a11, Application.OpenURL opens url in a new browser tab. In previous versions, Application.OpenURL opens url in the same browser tab, which terminates the running Unity application.

So from now on, Application.OpenUrl will open the url in a new tab, with an ugly warning from the browser saying a popup was blocked (but that is another story).

How to open a URL from WebGL in the same page?

So if you are between the 1% of the people who is actually looking to redirect the page to another location, this is a possible solution.

We will interact with the scripts in the browser to perform an old good javascript redirect. For that we will have to create a jslib file as is explained in the documentation here.

First, you will have to create a folder Plugins under your Assets folder, and there place a text file with the extension “.jslib”. Then open this file and write the following code in it:

var RedirectPage = {
    openUrl: function(link)
    {
        window.location.href = UTF8ToString(link);
    }
};

mergeInto(LibraryManager.library, RedirectPage);

And then from your C# code you can use it like this:

using System.Runtime.InteropServices;

public class ClickHandler : MonoBehaviour
{
    [SerializeField] string url;

    private void OnMouseDown()
    {
#if !UNITY_EDITOR
        openUrl(url);
#endif
    }

    [DllImport("__Internal")]
    private static extern void openUrl(string url);
}

And that’s it, you can replace the OnMouseDown with any method you need and is ready to go. Hope it helps!

If you have a comment, a question or a way to improve it, shoot me an email!


<
Previous Post
Warning “Use the new keyword if hiding was intended” in Unity’s MonoBehaviour class
>
Next Post
Analizing Unity Profiler frames with AI