The WebViewAsyncExecute method evaluates a JavaScript
expression within the context of the currently loaded page and returns
the result asynchronously. Unlike WebViewExecute, this method
does not block while waiting for the script to complete. Instead, the
result is delivered through the WEBVIEW_EVENT_SCRIPT_COMPLETED
event. The application can use the dwParam value to correlate the
completion event with the original request.
Based on how the project is configured, the AsyncExecute
method will either call WebViewAsyncExecuteA, which uses 8-bit
strings, or WebViewAsyncExecuteW, which uses Unicode strings. The
ANSI version expects the script to be a valid UTF-8 encoded
string and should not use extended ANSI characters from the system's
current code page. If the lpszJavaScript parameter contains
invalid Unicode characters, the method will fail and the last error
code will be set to ST_ERROR_INVALID_UNICODE.
The script must be valid JavaScript and you should not assume synchronous
execution. Results are returned by calling the GetWebResult method
which will provide you with the response from the script. The result
is provided as a JSON-formatted string, which may be either a quoted
string with escaped characters or a JSON object, depending on the
value returned by the script. Applications that expect structured data
should parse the returned string using a JSON parser.
Because script execution is dispatched to the underlying WebView2
control, this method will fail if navigation is still in progress.
Applications should always wait for the WEBVIEW_EVENT_NAVIGATION_COMPLETED
event before invoking script execution.
JavaScript must be enabled for scripts to execute. The
WEBVIEW_OPTION_ENABLE_SCRIPTING option must be specified
when the browser is created or attached to a window. If scripting is
disabled, this method will fail indicating that the operation is
not supported.
The AddStartupScript method can be used to insert
JavaScript which is executed whenever a new document is loaded.
VOID CALLBACK WebViewEventProc(HWND hWnd, UINT uEvent, WPARAM wParam, LPARAM lParam, DWORD_PTR dwParam)
{
CWebView *pWebView = reinterpret_cast<CWebView *>(dwParam);
if (!pWebView)
return;
if (uEvent == WEBVIEW_EVENT_SCRIPT_COMPLETED)
{
BOOL bSuccess = (BOOL)wParam;
if (bSuccess)
{
TCHAR szResult[512];
if (pWebView->GetWebResult(szResult, _countof(szResult)))
{
}
}
else
{
}
}
}
void RunExample(CWebView *pWebView)
{
if (!pWebView->AsyncExecute(_T("document.title"), reinterpret_cast<DWORD_PTR>(pWebView)))
{
DWORD dwError = pWebView->GetLastError();
// Handle the error condition
}
}