[solved] Get data from browser uri

Hi, I need to get some parameter from browser.

my js function, placed in html file,

//Example URI:
https://example.com/?product=shirt

const product = urlParams.get('product')
console.log(product);
// shirt
unityInstance.SendMessage("masterGO", "getProduct", product); //call unity method

In unity I have an empty GO, called masterGO which has a acript with class with method getProduct

    public void getProduct(string text){
        Debug.Log("Inputted string: " + text);
    }

What am I missing to get communication between browser - unity?

Thanks.

sample for get uri parameter.

// FILE: Assets/Plugins/WebGL/Location.cs
using System.Runtime.InteropServices;

public class Location
{
#if UNITY_WEBGL && !UNITY_EDITOR
    // get href from javascript.
    [DllImport("__Internal")]
    public static extern string href();
#else
    // for test
    public static string href() { return @"https://example.com/?product=shirt"; }
#endif
}
// FILE: Assets/Plugins/WebGL/Location.jslib
var Location = {
    href: function () {
        return allocate(intArrayFromString(location.href), 'i8', ALLOC_NORMAL);
    },
}
mergeInto(LibraryManager.library, Location);

to use.

using System;
using System.Web;
using UnityEngine;

public class Sample : MonoBehaviour
{
    void Start()
    {
        var uri = new Uri(Location.href());
        var query = HttpUtility.ParseQueryString(uri.Query);
        foreach (var k in query.AllKeys)
        {
            Debug.Log($"KEY( {k} ) VALUE( {query.Get(k)} )");
        }
    }
}
1 Like

@kou-yeung Thanks a lot!