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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Get the website url which is displaying the unity WebGL component

Discussion in 'WebGL' started by abgamers, Oct 26, 2016.

  1. abgamers

    abgamers

    Joined:
    Dec 22, 2009
    Posts:
    97
    Hi All,

    Here is the problem what im facing

    I have a WebGL Component which is hosted on a X server whose lets say "http://abc.com/webgl/mywebgl.html" is the unityWebGl source url.

    Now I have a client site which will be say www.xyz.com
    This client site is going to load mywebgl.html game in a iFrame.

    Now I want to detect / fetch the website which is using my webgl in my unity webgl module.

    I was under the impression that this can be found using Application.absoluteURL but for some reason its showing the source site path (http://abc.com/webgl/mywebgl.html) instead of client site url (www.xyz.com)

    I also tried using Application.srcValue in start function but this is returning empty "".


    Does any one know to to get the Client url which is loading my webgl component in their website.


    Thanks :)
     
  2. mikaelwallen

    mikaelwallen

    Joined:
    Jun 3, 2016
    Posts:
    56
    You can achieve this by passing the parent/client page url in the query string of the iframe src url.
    So iframe src in this case would be http://abc.com/webgl/mywebgl.html?client_url=http://www.xyz.com

    Now you just need to extract the client_url from Application.absoluteURL.

    And of course you don't need to hard code the src value. It can be added automatically via some JavaScript (on the client page) like:
    var iframe = document.getElementById("my-iframe");
    var queryStr = window.location.search;
    var url = window.location.href.replace(queryStr, "");
    iframe.src = iframe.src + "?client_url=" + url;
     
  3. abgamers

    abgamers

    Joined:
    Dec 22, 2009
    Posts:
    97
    Thanks for sharing the input @mikaelwallen, but in my case we cannot have parameters in the url. Although this is a very good option.

    It happens that I found a alternative solution using following code which needs to be added in unity exported html file between <script> tags. Obviously I need to handle cross communication between Browser & Unity WebGL modules.

    var url = (window.location != window.parent.location)
    ? document.referrer
    : document.location;

    This will give the current url mentioned in the Address bar of the browser. now this need to be passed to unity from current html javascript function.
     
  4. alexsuvorov

    alexsuvorov

    Unity Technologies

    Joined:
    Nov 15, 2015
    Posts:
    327
    Hello abgamers.

    Note that document.referrer will return the address of the embedding document, which may be different from the top document if there are multiple nested iframes in the embedding chain. You might also be interested in the window.top.location.href, which will return the address of the top window (which user can see in the browser address bar) assuming that the top window is from the same origin as your WebGL content (otherwise browser should throw a cross-origin access exception).

    You don't have to add this JavaScript code into the exported html, as it can be called from any place. The recommended way would be to create a .jslib plugin, which you can then use from your managed code. Take a look at the StringReturnValueFunction, which returns a string calculated in JavaScript to the managed code, described here: https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html
     
  5. abgamers

    abgamers

    Joined:
    Dec 22, 2009
    Posts:
    97
    Hi @alexsuvorov,
    As suggested I'm writing my own .jslib plugin and following the same StringReturnValueFunction example.

    Thanks for the input, really appreciated.
     
  6. the_greenlig

    the_greenlig

    Joined:
    Feb 5, 2013
    Posts:
    29
    @abgamers I'm looking for the same solution, how did it work out for you?

    [EDIT] I've put together a quick solution for anyone else that is chasing this problem and not quite sure how to deal with it.

    I've attached a .zip two scripts, URLTest.cs and GetURL.jslib. Put GetURL.jslib into the Plugins/WebGL/ folder in your project, and attach URLTest.cs to an empty object in your scene. If you deploy a webGL build, it will print the URL in the console using the GetURLFromPage() method. Very simple, does the trick.
     

    Attached Files:

    Last edited: Nov 11, 2016
  7. Immortaly007

    Immortaly007

    Joined:
    Nov 28, 2013
    Posts:
    2
    I had a similar issue where I needed to extract the query parameters from the URL from which the game is being played. Based on the code from @the_greenlig, 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
    ):
    Code (JavaScript):
    1.  
    2. mergeInto(LibraryManager.library, {
    3.  
    4.     GetURLFromPage: function () {
    5.         var returnStr = window.top.location.href;
    6.         var bufferSize = lengthBytesUTF8(returnStr) + 1
    7.         var buffer = _malloc(bufferSize);
    8.         stringToUTF8(returnStr, buffer, bufferSize);
    9.         return buffer;
    10.     },
    11.  
    12.     GetQueryParam: function(paramId) {
    13.         var urlParams = new URLSearchParams(location.search);
    14.         var param = urlParams.get(Pointer_stringify(paramId));
    15.         console.log("JavaScript read param: " + param);
    16.         var bufferSize = lengthBytesUTF8(param) + 1;
    17.         var buffer = _malloc(bufferSize);
    18.         stringToUTF8(param, buffer, bufferSize);
    19.         return buffer;
    20.     }
    21. });
    22.  
    To call the method, in C# I've created the following URLReader class/Component:

    Code (CSharp):
    1.  
    2. public class URLReader : MonoBehaviour
    3. {
    4.     [DllImport("__Internal")]
    5.     private static extern string GetURLFromPage();
    6.    
    7.     [DllImport("__Internal")]
    8.     private static extern string GetQueryParam(string paramId);
    9.  
    10.     public string ReadQueryParam(string paramId)
    11.     {
    12.         return GetQueryParam(paramId);
    13.     }
    14.    
    15.     public string ReadURL()
    16.     {
    17.         return GetURLFromPage();
    18.     }
    19. }
    20.  
     
  8. jinxed_byte

    jinxed_byte

    Joined:
    Mar 29, 2014
    Posts:
    17
    Be careful, if you are running in an iFrame. I got this one:
    Invoking error handler due to
    Uncaught SecurityError: Blocked a frame with origin "url......" from accessing a cross-origin frame​

    So I changed the jslib file, which works great for me
    var returnStr = (window.location != window.parent.location)
    ? document.referrer
    : document.location.href;

    You might also use a try / catch block around it to avoid uncaught exceptions.
     
  9. seanbiganski

    seanbiganski

    Joined:
    Aug 17, 2016
    Posts:
    30
    This helped me out but it needed an update.

    Then, add this to the top of your class:

    Code (CSharp):
    1. [DllImport("__Internal")]
    2. private static extern string GetURLFromPage();
    And you can call GetURLFromPage as a regular method.
     

    Attached Files:

    diego_mellizo and efge like this.
  10. luca_greci

    luca_greci

    Joined:
    Mar 27, 2017
    Posts:
    1
    Can you share your jslib file?
     
  11. malviyanpawan

    malviyanpawan

    Joined:
    Oct 24, 2013
    Posts:
    7
    Hi All,
    Thank for your support I also have the same issue.
    I have to fetch the referanc_AccessToken and AccessToken from the query string.
    With your help I'm able to fetch the browser url after that I split that to fetch both.

    First I upload the java script file through which I fetch the url.
    save this asGetURL.jslib in /Assets/Plugins/WebGL



    mergeInto(LibraryManager.library, {

    GetURLFromPage: function () {
    var returnStr = window.top.location.href;
    var bufferSize = lengthBytesUTF8(returnStr) + 1
    var buffer = _malloc(bufferSize);
    stringToUTF8(returnStr, buffer, bufferSize);
    return buffer;
    }
    });

    Now I share the test.cs file which i used to
    fetch the referanc_AccessToken and AccessToken =============



    using UnityEngine;
    using System.Runtime.InteropServices;
    using System;

    public class URLTest : MonoBehaviour
    {
    [DllImport("__Internal")]
    private static extern string GetURLFromPage();

    string url = "https://game.lernip.com/index.html?...rAEAqacAwe-QKIxUCam6PvM1u2r63O5_lSO4AzclyCheI";


    private void Start()
    {
    Debug.Log("App is running on the url>>>> " + ReadURL());
    /* int n = url.IndexOf('=');
    int length = url.Length;
    string str = null;
    Debug.Log("value of n "+n);
    Debug.Log("length of string " + (length-1));
    str = url.Substring((n+1), (length-n-1));
    Debug.Log("access token is:; "+ str);*/

    if(ReadURL().Contains("x-access-token="))
    {
    string[] stringSeparators = new string[] { "x-access-token=", "&x-refresh-token=" };
    //string[] tokens = url.Split(stringSeparators, StringSplitOptions.None);
    string[] tokens = ReadURL().Split(stringSeparators, StringSplitOptions.None);
    /*foreach (string firstName in tokens)
    Debug.LogError(firstName);*/

    string xaccesstoken = tokens[1];
    string referancAccessToken = tokens[2];

    Debug.LogError(xaccesstoken);
    Debug.LogError(referancAccessToken);
    }
    else
    {
    Debug.LogError("x-access-token= not contain");
    }



    }



    public string ReadURL()
    {
    return GetURLFromPage();
    }


    }
     
  12. ihamza301

    ihamza301

    Joined:
    Mar 28, 2019
    Posts:
    1
    Hi guys,
    The solution you guys proposed worked fine on Android and all other platforms except IOS devices. Have anyone of you tried it?
    Please share the solution for that as well if you have any.
    Thanks
     
  13. chgeorgiadis

    chgeorgiadis

    Joined:
    Jan 30, 2018
    Posts:
    50
    So, you are using something like this?

    GetURLFromPage: function () {
    var returnStr = (window.location != window.parent.location)
    ? document.referrer
    : document.location.href;
    var bufferSize = lengthBytesUTF8(returnStr) + 1
    var buffer = _malloc(bufferSize);
    stringToUTF8(returnStr, buffer, bufferSize);
    return buffer;
    }
     
  14. jinxed_byte

    jinxed_byte

    Joined:
    Mar 29, 2014
    Posts:
    17
    So, I just stepped on my own reply from a few years back and made it work again. For you (or me again in the future :))

    This is my JsLib file (UrlGetter.jslib)

    var GetUrl = {
    GetURLFromPage: function () {
    var returnStr = "not found";
    try{
    returnStr = (window.location != window.parent.location)
    ? document.referrer : document.location.href;
    } catch (error) {
    console.error('Error while getting Url: '+ error);
    }

    var bufferSize = lengthBytesUTF8(returnStr) + 1;
    var buffer = _malloc(bufferSize);
    stringToUTF8(returnStr, buffer, bufferSize);
    return buffer;
    }
    };
    mergeInto(LibraryManager.library, GetUrl);


    This is my C# Script (JsLib.cs):
      public static class JavaLib
    {
    #if UNITY_WEBGL && !UNITY_EDITOR
    [DllImport("__Internal")]
    private static extern string GetURLFromPage();

    [DllImport("__Internal")]
    private static extern string GetString();

    #else
    private static string GetURLFromPage() => "Sample Url";

    private static string GetString() => "String";
    #endif

    public static string UrlFromPage() => GetURLFromPage();

    public static string String() => GetString();
    }
     
    neckkeys and muzhigg like this.