Click here to Skip to main content
15,867,453 members
Articles / Web Development / HTML

Send and Receive Message through WebView2 to/from Your Website

Rate me:
Please Sign up or sign in to vote.
5.00/5 (6 votes)
1 Mar 2021CPOL4 min read 35.1K   1.3K   10   14
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)


Written By
Technical Lead
Switzerland Switzerland
Hello,

I am Ayush Chaudhary from the beautiful country of India. I have over 13 years of experience with application design and development. For 5 years, I have been living in Switzerland and working here as a Technical Consultant in a nice Swiss Company.

In my career, I have been working with many technologies, but trust me I am not sure which one is my favorite. I am confused between C#, Java, C++, MS SQL, IBM Informix, Android development, and many more.


Comments and Discussions

 
QuestionHow to interact with JavaScript function from C++ Pin
tsjakkaa23-Mar-23 19:34
tsjakkaa23-Mar-23 19:34 
AnswerRe: How to interact with JavaScript function from C++ Pin
Ayush Swiss23-Mar-23 22:27
Ayush Swiss23-Mar-23 22:27 
GeneralRe: How to interact with JavaScript function from C++ Pin
tsjakkaa24-Mar-23 0:16
tsjakkaa24-Mar-23 0:16 
Questionbeforeprint / afterprint Pin
Andrew Truckle15-Mar-23 6:14
professionalAndrew Truckle15-Mar-23 6:14 
AnswerRe: beforeprint / afterprint Pin
Ayush Swiss23-Mar-23 22:28
Ayush Swiss23-Mar-23 22:28 
QuestionC# version off sending a message from web Pin
Member 1413107621-May-22 20:01
Member 1413107621-May-22 20:01 
QuestionC# version of your article. Pin
Member 1418491116-Jul-21 7:07
Member 1418491116-Jul-21 7:07 
AnswerRe: C# version of your article. Pin
Ayush Swiss22-Sep-21 21:37
Ayush Swiss22-Sep-21 21:37 
GeneralMy vote of 5 Pin
tugrulGtx2-Mar-21 9:57
tugrulGtx2-Mar-21 9:57 
GeneralRe: My vote of 5 Pin
Ayush Swiss2-Mar-21 21:43
Ayush Swiss2-Mar-21 21:43 
GeneralRe: My vote of 5 Pin
Ayush Swiss2-Mar-21 21:25
Ayush Swiss2-Mar-21 21:25 
SuggestionArchive Pin
Rick York1-Mar-21 5:58
mveRick York1-Mar-21 5:58 
GeneralRe: Archive Pin
Ayush Swiss1-Mar-21 8:11
Ayush Swiss1-Mar-21 8:11 
I updated the solution, and now it's only 144 KB.

Thanks, Next time I will keep it in mind.
Thumbs Up | :thumbsup:
GeneralRe: Archive Pin
Rick York1-Mar-21 8:21
mveRick York1-Mar-21 8:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.