top of page
Search
  • RorschachGames

Unity WebGL & UnityWebRequest Cookies

Updated: Jun 30, 2021

We recently created a webGL game that is up on our game site right now. Like any webGL game that interacts with a back-end server, we wanted to be able to save data and know who was requesting any information from us and be able to save a character's progress.


During development, we worked extensively within the Unity Editor and we were able to initiate a web session by logging in. Every call to our server would transmit our cookie information and our user account would know who we were. Even as we tested against another web browser client, sessions would persist and testing would go well.


The real issue started when we played our game exclusively through a web browser. We started getting CORS errors and scrambled to find the appropriate headers to set on the web servers. Then we started viewing something peculiar. UnityWebRequest objects were not saving our cookie information due to security restrictions; both self-imposed and those from the browser.


The work around was to utilize a ".jslib" file and interface with the web browser directly. A Unity webGL build apparently uses the host web browser's cookie store. So as a work around, we pieced together from various StackOverflow and Unity Forum posts, to come up with the following. This is code from a ".jslib" for our project:

JSLogin: function (url,formdata){

var jsURL = Pointer_stringify(url);

var jsFormData = Pointer_stringify(formdata);


var xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function(){

if(this.readyState == 4 && this.status == 200){

console.log(xhttp.responseText);

}

};


xhttp.open("POST",jsURL,true);

xhttp.withCredentials = true;

xhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");

xhttp.send(jsFormData);

},


I made the call from a Monobehaviour class:


using System.Runtime.InteropServices;

//Declare below inside the class body

[DllImport("__Internal")]

private static extern void JSLogin(string url,string formdata);


The above, since the call was being made through the web browser by using an XMLHttpRequest object, was enough to write the cookie to the cookie store. Every other web request made after login was able to utilize the UnityWebRequest object without any issues and our server session was persisted.

(Website has been shut down)


1,618 views3 comments

Recent Posts

See All

VR with Horizon Avatars and Unity

We were recently tasked with creating a VR experience in a high school class room setting. Each person needed to be represented by a unique avatar, but the project had a tight budget. We decided to pi

Animatronics it is

I'm going to build an Animatronic Arm. The idea is that it would eventually allow me to create a life sized Halloween scene of Sleepy Hallow. I've played around with Arduino already so I'll hook it up

bottom of page