React app inside WebView2 cannot communicate with host application

12 Andree 20 Reputation points
2025-11-25T16:00:30.6933333+00:00

I am embedding a React JS web app inside a WebView2 control. I would like to implement simple two-way communication:React sends a message to the host (e.g., button click).The host calls a function inside React and updates the UI.

Can you please guide me on the easiest way to achieve this? Any example or best practice would be helpful. Thank you!

Microsoft Edge | Microsoft Edge development
0 comments No comments
{count} votes

Answer accepted by question author
  1. Jay Pham (WICLOUD CORPORATION) 3,060 Reputation points Microsoft External Staff Moderator
    2025-11-26T06:05:44.3033333+00:00

    I have created a simple project that demonstrates how to set up a Windows desktop application using WebView2 to host a React frontend, with two‑way communication between the React app and the C# WPF application.

    You can choose from the following versions:

    • .NET 6+ SDK
    • Node.js 18+
    • WebView2 Runtime
    1. React Frontend

    Here this is my set-up you can consult Create React App

    
    npm create vite@latest my-app -- --template react-ts
    
    cd my-app
    
    npm install
    
    

    App.tsx

    
    import { useState, useEffect } from 'react'
    
    function App() {
    
      const [isWebView2, setIsWebView2] = useState(false)
    
      const [message, setMessage] = useState('Waiting for host...')
    
      useEffect(() => {
    
        setIsWebView2(!!(window as any).chrome?.webview)
    
        window.addEventListener('message', (event) => {
    
          const data = JSON.parse(event.data)
    
          if (data.type === 'UPDATE') {
    
            setMessage(data.text)
    
          }
    
        })
    
      }, [])
    
      const sendToHost = () => {
    
        if (isWebView2) {
    
          (window as any).chrome.webview.postMessage(JSON.stringify({
    
            type: 'BUTTON_CLICK',
    
            data: 'Hello from React!'
    
          }))
    
        }
    
      }
    
      return (
    
        <div style={{ padding: '20px', fontFamily: 'Arial' }}>
    
          <h1>WebView2 + React Demo</h1>
    
          <div style={{ 
    
            padding: '10px', 
    
            background: isWebView2 ? '#d4edda' : '#f8d7da',
    
            borderRadius: '5px',
    
            marginBottom: '20px'
    
          }}>
    
            Environment: {isWebView2 ? 'WebView2' : 'Browser'}
    
          </div>
    
          <button 
    
            onClick={sendToHost}
    
            style={{
    
              padding: '10px 20px',
    
              background: '#007bff',
    
              color: 'white',
    
              border: 'none',
    
              borderRadius: '5px'
    
            }}
    
          >
    
            Send to Host
    
          </button>
    
          <div style={{ marginTop: '20px', padding: '10px', background: '#f8f9fa' }}>
    
            <strong>Host Message:</strong> {message}
    
          </div>
    
        </div>
    
      )
    
    }
    
    export default App
    
    

    Start React

    
    npm run dev
    
    
    1. C# Host Application

    Create Project

    
    dotnet new winforms -n WebView2Host
    
    cd WebView2Host
    
    dotnet add package Microsoft.Web.WebView2
    
    dotnet add package System.Text.Json
    
    

    MainForm.cs

    
    using Microsoft.Web.WebView2.WinForms;
    
    using Microsoft.Web.WebView2.Core;
    
    using System.Text.Json;
    
    public partial class MainForm : Form
    
    {
    
        private WebView2 webView;
    
        private Button sendBtn;
    
        public MainForm()
    
        {
    
            InitializeComponent();
    
            SetupWebView();
    
        }
    
        private void InitializeComponent()
    
        {
    
            this.Size = new Size(800, 600);
    
            this.Text = "WebView2 + React Demo";
    
            sendBtn = new Button
    
            {
    
                Text = "Send to React",
    
                Size = new Size(150, 30),
    
                Location = new Point(10, 10)
    
            };
    
            sendBtn.Click += (s, e) => SendToReact();
    
            webView = new WebView2 { Dock = DockStyle.Fill };
    
            var panel = new Panel { Height = 50, Dock = DockStyle.Top };
    
            panel.Controls.Add(sendBtn);
    
            this.Controls.Add(webView);
    
            this.Controls.Add(panel);
    
        }
    
        private async void SetupWebView()
    
        {
    
            await webView.EnsureCoreWebView2Async();
    
            webView.CoreWebView2.WebMessageReceived += (s, e) =>
    
            {
    
                var message = JsonSerializer.Deserialize<dynamic>(e.TryGetWebMessageAsString());
    
                MessageBox.Show($"React says: {message}");
    
            };
    
            webView.CoreWebView2.Navigate("http://localhost:5173");
    
        }
    
        private void SendToReact()
    
        {
    
            var message = new { type = "UPDATE", text = $"Hello from C#! {DateTime.Now:HH:mm:ss}" };
    
            webView.CoreWebView2.PostWebMessageAsString(JsonSerializer.Serialize(message));
    
        }
    
    }
    
    

    Program.cs

    
    namespace WebView2Host;
    
    static class Program
    
    {
    
        [STAThread]
    
        static void Main()
    
        {
    
            ApplicationConfiguration.Initialize();
    
            Application.Run(new MainForm());
    
        }
    
    }
    
    
    1. Run

    Terminal 1: React

    
    npm run dev
    
    

    User's image

    Terminal 2: C#

    
    dotnet run
    
    
    1. Test
    2. Click "Send to Host" in React → C# shows message
    3. Click "Send to React" in C# → React updates message
    4. Two-way communication working!

    User's image

    Quick Test (Browser Only)

    Open React app → F12 Console → Paste:

    
    // Simulate host message
    
    window.postMessage('{"type":"UPDATE","text":"Test from console!"}', '*');
    
    

    Build Production

    
    React
    
    npm run build
    
    C# (single exe)
    
    dotnet publish -c Release -r win-x64 --self-contained -p:PublishSingleFile=true
    
    

    Common Issues

    • WebView2 not found: Install WebView2 Runtime
    • React not loading: Check if dev server is running
    • Messages not working: Open F12 to debug

    This is just a reference approach, so feel free to review and comment on it. I’ve also attached some official Microsoft documentation here

    The method I gave you earlier (postMessage + ExecuteScriptAsync) is exactly the one Microsoft recommends as the simplest and most reliable in all of the above official docs.

    Hopefully, the above information will help you solve the problem.


1 additional answer

Sort by: Most helpful
  1. Q&A Assist
    2025-11-25T16:00:44.03+00:00
    AI generated content. This question contains an answer created with AI from Q&A Assist. Learn more

    To implement two-way communication between a React app embedded in a WebView2 control and the host application, you can use the postMessage method for sending messages from the React app to the host and the ICoreWebView2::PostWebMessageAsString or ICoreWebView2::PostWebMessageAsJSON methods for sending messages from the host to the React app.

    Here’s a basic outline of how to achieve this:

    1. Sending Messages from React to the Host

    In your React app, you can send a message to the host application when a button is clicked:

    function sendMessageToHost() {
        window.chrome.webview.postMessage('Hello from React!');
    }
    
    <button onClick={sendMessageToHost}>Send Message</button>
    

    2. Receiving Messages in the Host Application

    In your host application (C++), you need to register an event handler to receive messages from the React app:

    void OnWebMessageReceived(ICoreWebView2* sender, ICoreWebView2WebMessageReceivedEventArgs* args) {
        HSTRING message;
        args->GetWebMessageAsString(&message);
        // Process the message received from React
    }
    
    webView->add_WebMessageReceived(OnWebMessageReceived, &eventToken);
    

    3. Sending Messages from the Host to React

    To call a function inside the React app from the host, you can inject a script into the WebView2 control:

    std::wstring script = L"window.handleMessageFromHost('Update UI');";
    webView->ExecuteScript(script.c_str(), nullptr);
    

    In your React app, define the handleMessageFromHost function to update the UI:

    window.handleMessageFromHost = function(message) {
        // Update the UI based on the message
        console.log(message);
    };
    

    Summary

    This setup allows you to send messages back and forth between your React app and the host application. Make sure to handle the messages appropriately in both the React app and the host application to ensure smooth communication.


    References:

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.