Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Send and Receive Message through WebView2 to/from Your Website

5.00/5 (6 votes)
1 Mar 2021CPOL4 min read 40.6K   1.4K  
Establish the communication between WebView2 and JavaScript by which you can send and receive the message via WebView2
In this article, I will show you how to run WebView2 in your dialog-based applications. You will also see how you can send and receive the message to/from your website. You can directly invoke the JavaScript method, also the same way JavaScript can send the WebMessage to a C++ application. It's very very simple.

The HTML file which I use in this example is available in Release/Debug folder. So you don't need to worry about the path or its location.

Introduction

Now things are changing with the new Edge WebView2, it's a fast, modern, and Chromium-based browser. Now this will be used more and more in future projects.

In today's article, I will show you how you can directly invoke the JavaScript method, also the same way JavaScript can send the WebMessage to a C++ application. It's very very simple.

Background

Technology is changing very fast, so are browsers. Internet Explorer is lagging behind in comparison with other modern browsers like Chrome and Mozilla. To cover this up, Microsoft has now switched to Chromium-based Edge.

Using the Code

If you wonder how we use WebView2 in our C++ MFC-based applications, then first you should check my previous article on CodeProject. So, I am assuming that you know how to make the WebView2 application work with MFC C++ applications.

Call JavaScript Method or Script

First, we will focus on how to call a JavaScript method directly from a C++ application. Below, you can see a JavaScript method in my webpage.

JavaScript
function MessageReceived(Message)
{
   alert('HTML Page Popup :'+Message);
}

And here, we have one method in our C++ application. In this method, using m_webView (which is the WebView2 object) object, we can execute the JavaScript code directly.

Here, you can see that I am calling a function called "MessageReceived", this is the above JavaScript message.

JavaScript
void CEdgeBrowserAppDlg::SendMessageClicked()
{
    m_webView->ExecuteScript(L"MessageReceived
    ('Ayush sent a message from C++ application')", 
    Callback<ICoreWebView2ExecuteScriptCompletedHandler>
    (this, &CEdgeBrowserAppDlg::ExecuteScriptResponse).Get());
}

Or you can show an alert box using the below code:

JavaScript
void CEdgeBrowserAppDlg::SendMessageClicked() 
{  
   m_webView->ExecuteScript(L"alert('Ayush sent a message from C++ application')", 
   Callback<ICoreWebView2ExecuteScriptCompletedHandler>
   (this, &CEdgeBrowserAppDlg::ExecuteScriptResponse).Get()); 
} 

Or you can read the whole document using the below code:

JavaScript
void CEdgeBrowserAppDlg::SendMessageClicked()
{  
  m_webView->ExecuteScript(L"document.documentElement.outerHTML", 
  Callback<ICoreWebView2ExecuteScriptCompletedHandler>
  (this, &CEdgeBrowserAppDlg::ExecuteScriptResponse).Get());
} 

If you want to get any response from JavaScript, for example, in the third example, document.documentElement.outerHTML, we want to read the whole HTML code of the page. Then, we can access this response in ExecuteScriptResponse() method.

You can get the response from the result param.

JavaScript
HRESULT CEdgeBrowserAppDlg::ExecuteScriptResponse(HRESULT errorCode, LPCWSTR result)
{
    AfxMessageBox(L"C++ Application Popup : Message Sent Successfully");
    return S_OK;
}

Call C++ Method

In order to call the C++ method, we just need to write one line of code in JavaScript. Below, you can see a JavaScript method called SendMessage. And can see how we post a message to the web view.

JavaScript
function SendMessage() 
{
     var val = document.getElementById("txt").value;
     window.chrome.webview.postMessage(val);     
}

In C++, we must have an incoming message handler method by which we can retrieve the message sent by JavaScript.

So, the first thing to do is invoke the handler by using these two lines in OnCreateCoreWebView2ControllerCompleted method, just before we navigate to the page.

C++
EventRegistrationToken token;
m_webView->add_WebMessageReceived(Callback<ICoreWebView2WebMessageReceivedEventHandler>
(this, &CEdgeBrowserAppDlg::WebMessageReceived).Get(), &token);

The second is the method, which will be called when a new message will come.

C++
HRESULT CEdgeBrowserAppDlg::WebMessageReceived
(ICoreWebView2* sender, ICoreWebView2WebMessageReceivedEventArgs* args)
{
    LPWSTR pwStr;
    args->TryGetWebMessageAsString(&pwStr);
    CString receivedMessage = pwStr;
    if (!receivedMessage.IsEmpty())
    {
        AfxMessageBox("This message came from Javascript : " + receivedMessage);
    }
    return S_OK;
}

That's it, we are good to go now and test the application. First, you can see how this basic application looks like.

Here, we can see one very basic HTML page in WebView2 in which we have one text box and a button to send the message to C++ app. Also, there is one Menu option Send Message to HTML Page to send messages to our HTML/website.

Image 1

Now, we typed a message in the text box and click on "Send Message"

Image 2

We can see that the message is received by WebView2 means C++ application.

Now, we will do the opposite and send messages to the HTML page. In order to do that, there is one Menu option Send Message to HTML Page, just click on it.

Image 3

Once we click, a message will be received by the Web Page.

Image 4

If you want the response of the script you executed, then you can get it in the below method:

C++
HRESULT CEdgeBrowserAppDlg::ExecuteScriptResponse(HRESULT errorCode, LPCWSTR result)
{
    AfxMessageBox(L"C++ Application Popup : Message Sent Successfully");
    return S_OK;
}

You can process the response as you want.

Image 5

Here, I am just showing a message box that message is sent successfully.

Isn't it very cool and easy? Let me know in the comments.

And if it helps you a bit, then please rate this article as you wish.

Prerequisites

WebView2 supports the following programming environments:

  • Win32 C/C++ (GA)
  • .NET Framework 4.6.2 or later
  • .NET Core 3.1 or later
  • .NET 5
  • WinUI 3.0 (Preview)

Make sure you have installed both Microsoft Edge (Chromium) and the WebView2 SDK installed on supported OS (currently Windows 10, Windows 8.1, and Windows 7).

You must have Visual Studio 2015 or later with C++ support installed.

Thank you very much

Points of Interest

My last article WebView2 Edge Browser in MFC C++ has helped so many people and it encouraged me to share my knowledge with others because that knowledge is useless if it's not distributed or shared with others.

History

  • 1st March, 2021: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)