Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

[solved] Get data from browser uri

Discussion in 'WebGL' started by franMx, Sep 23, 2020.

  1. franMx

    franMx

    Joined:
    May 27, 2013
    Posts:
    30
    Hi, I need to get some parameter from browser.


    my js function, placed in html file,
    Code (CSharp):
    1.  
    2. //Example URI:
    3. https://example.com/?product=shirt
    4.  
    5. const product = urlParams.get('product')
    6. console.log(product);
    7. // shirt
    8. unityInstance.SendMessage("masterGO", "getProduct", product); //call unity method
    9.  
    In unity I have an empty GO, called masterGO which has a acript with class with method getProduct

    Code (CSharp):
    1.     public void getProduct(string text){
    2.         Debug.Log("Inputted string: " + text);
    3.     }

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

    Thanks.
     
  2. kou-yeung

    kou-yeung

    Joined:
    Sep 5, 2016
    Posts:
    30
    sample for get uri parameter.

    Code (CSharp):
    1. // FILE: Assets/Plugins/WebGL/Location.cs
    2. using System.Runtime.InteropServices;
    3.  
    4. public class Location
    5. {
    6. #if UNITY_WEBGL && !UNITY_EDITOR
    7.     // get href from javascript.
    8.     [DllImport("__Internal")]
    9.     public static extern string href();
    10. #else
    11.     // for test
    12.     public static string href() { return @"https://example.com/?product=shirt"; }
    13. #endif
    14. }
    15.  
    Code (JavaScript):
    1. // FILE: Assets/Plugins/WebGL/Location.jslib
    2. var Location = {
    3.     href: function () {
    4.         return allocate(intArrayFromString(location.href), 'i8', ALLOC_NORMAL);
    5.     },
    6. }
    7. mergeInto(LibraryManager.library, Location);
    to use.
    Code (CSharp):
    1. using System;
    2. using System.Web;
    3. using UnityEngine;
    4.  
    5. public class Sample : MonoBehaviour
    6. {
    7.     void Start()
    8.     {
    9.         var uri = new Uri(Location.href());
    10.         var query = HttpUtility.ParseQueryString(uri.Query);
    11.         foreach (var k in query.AllKeys)
    12.         {
    13.             Debug.Log($"KEY( {k} ) VALUE( {query.Get(k)} )");
    14.         }
    15.     }
    16. }
     
    franMx likes this.
  3. franMx

    franMx

    Joined:
    May 27, 2013
    Posts:
    30