Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
3
Question by anilhdas · Dec 14, 2016 at 04:09 PM · javascriptwebglparametersurlurl schemes

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

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

4 Replies

· Add your reply
  • Sort: 
avatar image
2
Best Answer

Answer by Landern · Dec 14, 2016 at 04:13 PM

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.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image anilhdas · Dec 20, 2016 at 08:11 AM 0
Share

Thanks @Landern, it helped me jump into the problem and find a way. Cheers

avatar image bibbis anilhdas · Jul 01, 2018 at 08:34 PM 0
Share

Ok. Thanks for sharing what you learned...

avatar image
7

Answer by Bunny83 · Jul 01, 2018 at 11:23 PM

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


Comment
Add comment · Show 10 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image tomekkie · Jul 02, 2018 at 06:11 AM 0
Share

Nice, but the method it uses: Application.ExternalEval has became obsolete.

avatar image c-pinto · Feb 11, 2019 at 10:04 AM 0
Share

Thanks. it works really well!

avatar image Bunny83 c-pinto · Feb 11, 2019 at 02:41 PM 1
Share

Note that i've posted an update since the "old" way (using ExternalEval) may no longer work in the future as Unity has deprecated this API. I've linked a newer version that is using an embedded JSLib. Though the new version works a bit different and is even simpler on the C# side. (also i've fixed my example link).

avatar image c-pinto Bunny83 · Feb 11, 2019 at 02:53 PM 0
Share

Great stuff! Thank you for the update.

avatar image kmeboe · Jul 10, 2019 at 06:33 PM 0
Share

This works perfectly! Thank you so much for your work to help the community.

avatar image Sakuwwz · Nov 20, 2019 at 11:46 AM 0
Share

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

avatar image Bunny83 Sakuwwz · Nov 20, 2019 at 02:22 PM 0
Share

As I said in my answer if you have a search parameter you can use GetSearchParameters() which returns a dictionary with the whole search string being parsed into name=value pairs.

So you can do:

 var parameters = URLParameters.GetSearchParameters();
 string site;
 if (parameters.TryGetValue("site", out site))
 {
     // use "site" here
 }
 else
 {
     // no parameter with name "site" found
 }

If you want to use a default value in case no site parameter was passed you can simply use

 var parameters = URLParameters.GetSearchParameters();
 string site;
 if (!parameters.TryGetValue("site", out site))
 {
     // set default value here
     site = "default site";
 }
 // use "site" here
avatar image Sakuwwz Bunny83 · Nov 21, 2019 at 04:00 AM 0
Share

hi @Bunny83 That's works perfectly. Thanks for sharing your knowledge with us. Best regards...

avatar image harshkapoor97 · Jul 08, 2021 at 03:59 PM 0
Share

I am unable to get this to work can you please help me?

it prints 42 only everytime.

It doesn't return the string which i want it to return from the URL:(

avatar image Bunny83 harshkapoor97 · Jul 08, 2021 at 04:05 PM 0
Share

Please, ask a seperate question if you have an issue. Also in your question you have to add more details what exactly you're doing and also which version of the script you're using. Also do you actually test this in an actual WebGL build? There are countless of open questions in regard to your specific issue that can not be answered in a comment here. That's why we have Questions and Answers. So if you have a question, please, post a seperate question. Feel free to add a cross link to this question. However don't forget to actually provide more details about your setup and your actual issue

avatar image
6

Answer by tomekkie2 · Dec 14, 2016 at 04:27 PM

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


Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image tomekkie2 · Dec 14, 2016 at 04:30 PM 0
Share

Like in the example here: http://virtualplayground.d2.pl/WebGL/st15/?4x3_cederroth

avatar image
0

Answer by malviyanpawan · Aug 23, 2021 at 11:00 AM

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

}

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

15 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

WebGL - InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable 1 Answer

Mute audio in webgl outside of the player. 0 Answers

Webgl : How to use javascript sharing function 0 Answers

Javascript controlling Mecanim? 1 Answer

Can someone help me fix my Javascript for Flickering Light? 6 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges