Unity WebGL ↔ Browser Communication: Simple Guide


Overview
Unity WebGL can send data to browser JavaScript and receive data back. Here's how:
Unity C# ←→ Browser JavaScript
↓ ↓
.jslib file → window.object
SendMessage ← JavaScript
1. Unity → Browser
Step 1: Create .jslib file
File: Assets/Plugins/WebGL/GameInterface.jslib
mergeInto(LibraryManager.library, {
SendToJS: function(stringPtr) {
var string = UTF8ToString(stringPtr);
if (window.GameInterface && window.GameInterface.receive) {
window.GameInterface.receive(string);
}
}
});
Step 2: Unity C# script
using UnityEngine;
using System.Runtime.InteropServices;
public class WebGLCommunicator : MonoBehaviour
{
[DllImport("__Internal")]
private static extern void SendToJS(string str);
public void SendToBrowser(string message)
{
#if UNITY_WEBGL && !UNITY_EDITOR
SendToJS(message);
#endif
}
// Send anything - convert to string first:
public void SendScore(int score) => SendToBrowser(score.ToString());
public void SendData(object data) => SendToBrowser(JsonUtility.ToJson(data));
}
Step 3: Browser JavaScript
<script>
window.GameInterface = {
receive: function(string) {
console.log("From Unity:", string);
// Parse string back to original type if needed:
// var number = parseInt(string);
// var object = JSON.parse(string);
}
};
</script>
Note: Anything can be sent between Unity and browser - just convert to string first, then parse back.
2. Browser → Unity
Unity C# (add this method)
// Method that JavaScript can call
public void ReceiveFromJS(string str)
{
Debug.Log("From Browser: " + str);
// Parse string back to original type if needed:
// int number = int.Parse(str);
// MyClass obj = JsonUtility.FromJson<MyClass>(str);
}
Browser JavaScript
let unityInstance = null; // Set when Unity loads
function sendToUnity(anything) {
if (unityInstance) {
// Convert anything to string
var string = typeof anything === 'string' ? anything : JSON.stringify(anything);
unityInstance.SendMessage('WebGLCommunicator', 'ReceiveFromJS', string);
}
}
// Send anything:
sendToUnity("Hello Unity");
sendToUnity(42);
sendToUnity({score: 100, level: 5});
sendToUnity([1, 2, 3, 4]);
sendToUnity(true);
Complete Setup Guide
Unity Setup:
Create folder structure:
Assets/ ├── Plugins/WebGL/GameInterface.jslib ├── Scripts/WebGLCommunicator.cs └── Scenes/GameScene.unity
Create GameObject: Empty GameObject named "WebGLCommunicator"
Attach Script: Add WebGLCommunicator.cs to the GameObject
Build Settings: File → Build Settings → WebGL → Build
Web Setup:
Unity Build Files: Copy Unity build folder to your web server
Create HTML file with Unity loader + communication code below
Test: Open in browser (must be served from web server, not file://)
npx http-server -p 8080 -o
Complete Minimal Example
Unity Files:
GameInterface.jslib:
mergeInto(LibraryManager.library, {
SendToJS: function(stringPtr) {
var string = UTF8ToString(stringPtr);
if (window.GameInterface) window.GameInterface.receive(string);
}
});
WebGLCommunicator.cs:
using UnityEngine;
using System.Runtime.InteropServices;
public class WebGLCommunicator : MonoBehaviour
{
[DllImport("__Internal")]
private static extern void SendToJS(string str);
void Start() => SendToBrowser("Game Started");
public void SendToBrowser(string str)
{
#if UNITY_WEBGL && !UNITY_EDITOR
SendToJS(str);
#endif
}
public void ReceiveFromJS(string str)
{
Debug.Log("From JS: " + str);
}
}
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Unity WebGL Communication</title>
</head>
<body>
<div id="unity-container">
<canvas id="unity-canvas"></canvas>
</div>
<button onclick="sendToUnity('Hello from browser!')">Send to Unity</button>
<script>
// Unity communication interface
window.GameInterface = {
receive: function(string) {
console.log("Unity says:", string);
}
};
let unityInstance = null;
function sendToUnity(anything) {
if (unityInstance) {
var string = typeof anything === 'string' ? anything : JSON.stringify(anything);
unityInstance.SendMessage('WebGLCommunicator', 'ReceiveFromJS', string);
}
}
// Load Unity
const buildUrl = "Build"; // Your Unity build folder
const config = {
dataUrl: buildUrl + "/YourGameName.data",
frameworkUrl: buildUrl + "/YourGameName.framework.js",
codeUrl: buildUrl + "/YourGameName.wasm",
};
createUnityInstance(document.querySelector("#unity-canvas"), config)
.then(instance => {
unityInstance = instance;
console.log("Unity loaded!");
});
</script>
</body>
</html>
Key Points
Unity → Browser: Use
.jslib
+[DllImport]
+window.object
Browser → Unity: Use
unityInstance.SendMessage(gameObject, method, data)
Data types: Everything travels as strings - convert as needed
Platform check: Always use
#if UNITY_WEBGL && !UNITY_EDITOR
GameObject name: Must match exactly in
SendMessage
That's it! This covers 90% of Unity-Browser communication needs.
Subscribe to my newsletter
Read articles from Tenith directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
