Sending messages from JavaScript to C#
3D WebView has a built-in window.vuplex.postMessage()
JavaScript API that you can use to send messages from JavaScript to C#. Since it's built into the browser, you don't need to include any additional libraries in the web page in order to utilize it.
Important note: the window.vuplex
JavaScript object is initially undefined and is added to the web page milliseconds after the page has finished loading. So, if your JavaScript needs to use the window.vuplex.postMessage()
API immediately after the page has loaded, it must check if the window.vuplex
object is defined and, if not, listen for the vuplexready
event on the global window object to detect when it has been added.
The following example illustrates how to use this JavaScript API in a page script or in a script executed via ExecuteJavaScript():
// The window.vuplex object is added milliseconds after the page finishes loading,
// so if sending a message immediately after the page load, it's necessary to check
// if it exists first. You can skip this step if you're sending a message long after the page has loaded.
if (window.vuplex) {
// The window.vuplex object already exists, so go ahead and send the message.
sendMessageToCSharp();
} else {
// The window.vuplex object hasn't been initialized yet, so listen for the
// vuplexready event to send the message when window.vuplex is initialized.
window.addEventListener('vuplexready', sendMessageToCSharp);
}
function sendMessageToCSharp() {
// This object passed to postMessage() automatically gets serialized as JSON
// and is emitted via the C# IWebView.MessageEmitted event. This API mimics the window.postMessage() API.
window.vuplex.postMessage({ type: 'greeting', message: 'Hello from JavaScript!' });
}
The following C# demonstrates how to receive that message in Unity using the IWebView.MessageEmitted event:
async void Start() {
// Get a reference to the webview: https://support.vuplex.com/articles/how-to-reference-a-webview
var webViewPrefab = GameObject.Find("WebViewPrefab").GetComponent<WebViewPrefab>();
// Wait for the WebViewPrefab to initialize because the WebViewPrefab.WebView property
// is null until the prefab has initialized.
await webViewPrefab.WaitUntilInitialized();
// Add a handler to the IWebView.MessageEmitted event.
webViewPrefab.WebView.MessageEmitted += (sender, eventArgs) => {
// > JSON received: { "type": "greeting", "message": "Hello from JavaScript!" }
Debug.Log("JSON received: " + eventArgs.Value);
};
}
Sending messages from C# to JavaScript
The process for sending messages from C# to JavaScript is very similar. Here's a C# script that uses the IWebView.PostMessage() method to send a message to JavaScript:
async void Start() {
// Get a reference to the webview: https://support.vuplex.com/articles/how-to-reference-a-webview
var webViewPrefab = GameObject.Find("WebViewPrefab").GetComponent<WebViewPrefab>();
// Wait for the WebViewPrefab to initialize because the WebViewPrefab.WebView property
// is null until the prefab has initialized.
await webViewPrefab.WaitUntilInitialized();
// Wait for the web page to finish loading. This step is important because
// any JavaScript that attaches a message event handler doesn't execute until
// the page has finished loading
await webViewPrefab.WebView.WaitForNextPageLoadToFinish();
// Send a message to JavaScript.
webViewPrefab.WebView.PostMessage("{\"type\": \"greeting\", \"message\": \"Hello from C#!\"}");
}
Starting with 3D WebView v4.11 (released in January 2025), JavaScript can receive messages from C# by listening for the vuplexmessage
event on the global window object, like this:
window.addEventListener('vuplexmessage', event => {
// > JSON received: { "type": "greeting", "message": "Hello from C#!" }
console.log('JSON received: ' + event.value);
});
For older versions of 3D Webview prior to v4.11 (before the introduction of the window vuplexmessage
event), JavaScript can receive messages by listening for the message
event on the window.vuplex
object like shown in the following example. Newer versions of 3D WebView are backward compatible and still support this approach, too:
if (window.vuplex) {
addMessageListener();
} else {
window.addEventListener('vuplexready', addMessageListener);
}
function addMessageListener() {
window.vuplex.addEventListener('message', event => {
let json = event.data;
// > JSON received: { "type": "greeting", "message": "Hello from C#!" }
console.log('JSON received: ' + json);
});
}
The advantage of the new vuplexmessage
approach is that the global window object is never undefined, so JavaScript can access it at anytime to add the event handler. In contrast, the window.vuplex
object is initially undefined after the page has loaded (as described above), so JavaScript must handle that by using the vuplexready
event to detect when the window.vuplex
object is added. An alternative to passing messages from C# to JavaScript is to instead use ExecuteJavaScript()
to execute JavaScript directly.
Other examples
Here are other examples that demonstrate passing messages from JavaScript to C# and vice versa:
- Blog article: How to create a UI in Unity using HTML
- 3D WebView's AdvancedWebViewDemo scene (AdvancedWebViewDemo.cs)
- 3D WebView's Keyboard UI
- The WebGL demo project
Limitations
2D WebView for WebGL has a limitation where it's unable to automatically add the window.vuplex
JavaScript API to a web page if the page is from a different domain than the Unity app. Please see this page for details and the solution.
Troubleshooting
If messages aren't being sent or received as expected, please check the following:
- Verify that your JavaScript is checking if window.vuplex exists and uses the vuplexready event like shown in this section. It may be that your script is trying to use window.vuplex before it is set.
- Use remote debugging to verify that your JavaScript is successfully attaching its message handler and calling vuplex.postMessage() as expected.
- Verify that your C# script is using WebViewPrefab.WaitUntilInitialized() to wait until the prefab has initialized before setting its MessageEmitted event handler, like shown in this section. Otherwise, WebViewPrefab.WebView may be
null
, which would trigger a NullReferenceException. - If your C# script sends a message to your JavaScript directly after the page finishes loading, it should wait until the JavaScript indicates that it has attached a message handler, otherwise the JavaScript may miss the message. For an example of this pattern, please see AdvancedWebViewDemo.cs from 3D WebView's AdvancedWebViewDemo scene.