Legacy Documentation: Version 5.0
WebGL performance considerations
WebGL Networking

WebGL: Interacting with browser scripting

Suggest a change

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Close

Sumbission failed

For some reason your suggested change could not be submitted. Please try again in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Close

Cancel

When building content for the web, you might need to communicate with other elements on your web page. Or you might want to implement functionality using Web APIs which Unity does not currently expose by default. In both cases, you need to directly interface with the browser’s JavaScript engine. Unity WebGL provides different methods to do this.

Calling between JavaScript code from Unity

The first is the same as for the Web Player. You can use the Application.ExternalCall() and Application.ExternalEval() functions to invoke JavaScript code on the embedding web page. To call methods on GameObjects in your content from browser JavaScript, you can use the following code:

SendMessage ('MyGameObject', 'MyFunction', 'foobar');

Calling JavaScript functions from a plugin

The other way to use browser JavaScript in your project is to add your JavaScript sources to your project, and then call those functions directly from your script code. To do so, place files with JavaScript code using the .jslib extension (as the normal .js would be picked up by the UnityScript compiler) into a “Plugins/WebGL” folder in your Assets folder. The file needs to have a syntax like this:

Assets/Plugins/WebGL/MyPlugin.jslib

var MyPlugin = {
    Hello: function()
    {
        window.alert("Hello, world!");
    },
    HelloString: function(str)
    {
        window.alert(Pointer_stringify(str));
    },
    PrintFloatArray: function(array, size)
    {
        for(var i=0;i<size;i++)
            console.log(HEAPF32[(array>>2)+size]);
    },
    AddNumbers: function(x,y)
    {
        return x + y;
    },
    StringReturnValueFunction: function()
    {
        var returnStr = "bla";
        var buffer = _malloc(returnStr.length + 1);
        writeStringToMemory(returnStr, buffer);
        return buffer;
    }
};

mergeInto(LibraryManager.library, MyPlugin);

Then you can call these functions from your C# scripts like this:

using UnityEngine;

public class NewBehaviourScript : MonoBehaviour {

    [DllImport("__Internal")]
    private static extern void Hello();

    [DllImport("__Internal")]
    private static extern void HelloString(string str);

    [DllImport("__Internal")]
    private static extern void PrintFloatArray(float[] array, int size);

    [DllImport("__Internal")]
    private static extern int AddNumbers(int x, int y);

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

    void Start() {
        Hello();
        
        HelloString("This is a string.");
        
        float[] myArray = new float[10];
        PrintFloatArray(myArray, myArray.Length);
        
        int result = AddNumbers(5, 7);
        Debug.Log(result);
        
        Debug.Log(StringReturnValueFunction());
    }
}

Simple numeric types can be passed to JavaScript in function parameters without requiring any conversion. Other data types will be passed as a pointer in the emscripten heap (which is really just a big array in JavaScript). For strings, you can use the Pointer_stringify helper function to convert to a JavaScript string. To return a string value you need to call _malloc to allocate some memory and the writeStringToMemory helper function to write a JavaScript string to it. If the string is a return value, then the il2cpp runtime will take care of freeing the memory for you. For arrays of primitive types, emscripten provides different ArrayBufferViews into it’s heap for different sizes of integer, unsigned integer or floating point representations of memory: HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64.

Calling C++ functions from a plugin

Since Unity compiles your sources into JavaScript from C++ code using emscripten, you can also write plugins in C or C++ code, and call these functions from C#. So, instead of the jslib file in the example above, you could have a c file like below in your project - it will automatically get compiled with your scripts, and you can call functions from it, just like in the JavaScript example above.

Assets/Plugins/WebGL/MyPlugin.c

#include <stdio.h>

void Hello ()
{
    printf("Hello, world!\n");
}

int AddNumbers (int x, int y)
{
    return x + y;
}

WebGL performance considerations
WebGL Networking