Using Microsoft Edge in a native Windows desktop app – part 5

This article is a new installment in the series about using the Webview2 control in a native application. In this post, I will show how to execute a JavaScript script.

Articles in this series:

The ICoreWebView2 interface contains a method called ExecuteScript. This method runs the provided script (JavaScript code) in the top-level document rendered by the web view. The method has two parameters: a string containing the JavaScript code and a completion handler (of the ICoreWebView2ExecuteScriptCompletedHandler type).

To see how this works, we will execute a script that retrieves the selected text from the current document. The JavaScript code to run for this purpose is:

window.getSelection().toString()

The following function (a member of the CWebBrowser class) runs this script. Upon completion, it calls a callback function, passing the return value as an argument.

void CWebBrowser::GetSelectedText(TextSelectionFunc callback)
{
   if (m_pImpl->m_webView != nullptr)
   {
      m_pImpl->m_webView->ExecuteScript(L"window.getSelection().toString()",
         Callback<ICoreWebView2ExecuteScriptCompletedHandler>(
            [callback](HRESULT error, PCWSTR result) -> HRESULT
            {
               if (error != S_OK) {
                  ShowFailure(error, L"ExecuteScript failed");
               }

               CW2T text(result);
               callback(CString(text.m_psz));

               return S_OK;
            }).Get());
   }
}

The TextSelectionFunc type is defined as follows:

using TextSelectionFunc = std::function<void(CString const &)>;

Here is a screenshot of the demo application using this function:

To see another example, let’s execute the following JavaScript code that changes the background color of the body of the document to red:

document.body.style.backgroundColor = "red"

We can provide the following (general-purpose) function in the CWebBrowser class to execute a script:

void CWebBrowser::ExecuteScript(CString const& code)
{
   if (m_pImpl->m_webView != nullptr)
   {
      m_pImpl->m_webView->ExecuteScript(CT2W(code).m_psz,
         Callback<ICoreWebView2ExecuteScriptCompletedHandler>(
            [](HRESULT error, PCWSTR result) -> HRESULT
            {
               if (error != S_OK) {
                  ShowFailure(error, L"ExecuteScript failed");
               }

               return S_OK;
            }).Get());
   }
}

The result of calling ExecuteScript(L"document.body.style.backgroundColor = \"red\"") is shown in the following images:

Try the app

You can download, build, and try the sample app for this series from here:

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.