How to detect something in a web page, like a button click?

If you want to detect something within a web page (for example: a button click), you can add JavaScript that detects it and sends a message to notify your C# script.

  • If it's a third party web page, you can inject additional JavaScript programmatically using IWebView.ExecuteJavaScript() or PageLoadScripts.
  • Or if the web page is one that you control (i.e. it's your website) you can add the JavaScript directly to the web page's source code.

The JavaScript needed depends on the particular web page and your goal. You can use remote debugging to inspect the web page and interact with its JavaScript console for development in order to determine the JavaScript needed. Here's a simple example that uses PageLoadScripts and message passing to detect when the first button on a page is clicked:

// https://developer.vuplex.com/webview/WebViewPrefab#WaitUntilInitialized
await webViewPrefab.WaitUntilInitialized();

// Add JavaScript that detects when the first button is clicked and sends a message to C#.
// https://developer.vuplex.com/webview/IWebView#PageLoadScripts
// https://support.vuplex.com/articles/how-to-send-messages-from-javascript-to-c-sharp
webViewPrefab.WebView.PageLoadScripts.Add(@"
    let button = document.getElementsByTagName('button')[0];
    button.addEventListener('click', () => {
        window.vuplex.postMessage('button clicked');
    });
");

// Receive the message sent by the JavaScript we injected.
// https://developer.vuplex.com/webview/IWebView#MessageEmitted
webViewPrefab.WebView.MessageEmitted += (sender, eventArgs) => {
    if (eventArgs.Value == "button clicked") {
        Debug.Log("The button was clicked!");
    }
};