{"pageContext":{"article":{"title":"How to send messages from JavaScript to C# and vice versa?","id":"how-to-send-messages-from-javascript-to-c-sharp","description":"An explanation of how to pass messages from JavaScript to C# and vice versa.","createdDate":"2020-04-25","updatedDate":"2022-10-04","content":"<h2 id=\"js-to-cs\">Sending messages from JavaScript to C#</h2>\n\n3D WebView has a built-in [window.vuplex.postMessage()](https://developer.vuplex.com/webview/IWebView#MessageEmitted) JavaScript API\nthat you can use to send messages from JavaScript to C#. Since it's built into the browser, you\ndon't need to include any 3rd party scripts in the page in order to utilize it. The following\nexample illustrates how to use this JavaScript API in a page script or in a script executed\nvia [ExecuteJavaScript()](https://developer.vuplex.com/webview/IWebView#ExecuteJavaScript):\n\n```\n// The window.vuplex object gets created when the page starts loading,\n// so we double-check that it exists before using it here.\n// You can skip this step if you're sending a message after the page has loaded.\nif (window.vuplex) {\n    // The window.vuplex object already exists, so go ahead and send the message.\n    sendMessageToCSharp();\n} else {\n    // The window.vuplex object hasn't been initialized yet because the page is still\n    // loading, so add an event listener to send the message once it's initialized.\n    window.addEventListener('vuplexready', sendMessageToCSharp);\n}\n\nfunction sendMessageToCSharp() {\n    // This object passed to postMessage() automatically gets serialized as JSON\n    // and is emitted via the C# MessageEmitted event. This API mimics the window.postMessage API.\n    window.vuplex.postMessage({ type: 'greeting', message: 'Hello from JavaScript!' });\n}\n```\n\nThe following C# demonstrates how to receive that message in Unity using the [MessageEmitted](https://developer.vuplex.com/webview/IWebView#MessageEmitted) event:\n\n```\nasync void Start() {\n    // This assumes that there's a WebViewPrefab already in the scene.\n    var webViewPrefab = GameObject.Find(\"WebViewPrefab\").GetComponent<WebViewPrefab>();\n    // Wait for the WebViewPrefab to initialize, because the WebViewPrefab.WebView property\n    // is null until the prefab has initialized.\n    await webViewPrefab.WaitUntilInitialized();\n    webViewPrefab.WebView.MessageEmitted += (sender, eventArgs) => {\n        // > JSON received: { \"type\": \"greeting\", \"message\": \"Hello from JavaScript!\" }\n        Debug.Log(\"JSON received: \" + eventArgs.Value);\n    };\n}\n```\n\n<h2 id=\"cs-to-js\">Sending messages from C# to JavaScript</h2>\n\nThe process for sending messages from C# to JavaScript is very similar.\nHere's a C# script that uses [PostMessage()](https://developer.vuplex.com/webview/IWebView#PostMessage)\nto send a message to JavaScript:\n\n```\n\nasync void Start() {\n\n    var webViewPrefab = GameObject.Find(\"WebViewPrefab\").GetComponent<WebViewPrefab>();\n    // Wait for the WebViewPrefab to initialize, because the WebViewPrefab.WebView property\n    // is null until the prefab has initialized.\n    await webViewPrefab.WaitUntilInitialized();\n    // Send a message after the page has loaded.\n    await webViewPrefab.WebView.WaitForNextPageLoadToFinish();\n    webViewPrefab.WebView.PostMessage(\"{\\\"type\\\": \\\"greeting\\\", \\\"message\\\": \\\"Hello from C#!\\\"}\");\n}\n```\n\nAnd here's some JavaScript that listens for a message through the `window.vuplex` object's\n`message` event:\n\n```\nif (window.vuplex) {\n    addMessageListener();\n} else {\n    window.addEventListener('vuplexready', addMessageListener);\n}\n\nfunction addMessageListener() {\n    window.vuplex.addEventListener('message', function(event) {\n        let json = event.data;\n        // > JSON received: { \"type\": \"greeting\", \"message\": \"Hello from C#!\" }\n        console.log('JSON received: ' + json);\n    });\n}\n```\n\nAn alternative to passing messages from C# to JavaScript is to instead use [ExecuteJavaScript()](https://developer.vuplex.com/webview/IWebView#ExecuteJavaScript)\nto execute JavaScript directly.\n\n<h2 id=\"examples\">Other examples</h2>\n\nHere are other examples that demonstrate passing messages from JavaScript to C# and vice versa:\n\n- Blog article: [How to create a UI in Unity using HTML](https://blog.vuplex.com/how-to-create-unity-ui-with-html)\n- 3D WebView's AdvancedWebViewDemo scene (AdvancedWebViewDemo.cs)\n- 3D WebView's [Keyboard UI](https://github.com/vuplex/unity-keyboard/blob/8e7cb70411a90f5a95de51abcbb4b1712173e0e4/src/components/Keyboard/index.tsx#L111)\n- The [WebGL demo project](https://github.com/vuplex/webgl-webview-demo/blob/master/Assets/Scripts/WebGLWebViewDemo.cs)\n\n<h2 id=\"limitations\">Limitations</h2>\n\n[2D WebView for WebGL](https://store.vuplex.com/webview/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](/articles/webgl-limitations/#cross-origin-messages) for details and the solution.\n\n<h2 id=\"troubleshooting\">Troubleshooting</h2>\n\nIf messages aren't being sent or received as expected, please check the following:\n\n- Verify that your JavaScript is checking if window.vuplex exists and uses the vuplexready event like shown [in this section](#js-to-cs). It may be that your script is trying to use window.vuplex before it is set.\n- Use [remote debugging](/articles/how-to-debug-web-content) to verify that your JavaScript is successfully attaching its message handler and calling vuplex.postMessage() as expected.\n- Verify that your C# script is using [WebViewPrefab.WaitUntilInitialized()](https://developer.vuplex.com/webview/WebViewPrefab#WaitUntilInitialized) to wait until the prefab has initialized before setting its MessageEmitted event handler, like shown in [this section](#cs-to-js). Otherwise, [WebViewPrefab.WebView](https://developer.vuplex.com/webview/WebViewPrefab#WebView) may be `null`, which would trigger a NullReferenceException.\n- 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."}}}