I am working on WebView2 using C .
Below is part of my HTML.
<div >
<form id="tenantform" action="about:blank" method="post" data-custom-validation="true" data-enable-shim="true">
<input id="field_name" type="text" name="field_name" >
<select Id="listvalue" name="listvalue">
<option value="A">A</option>
<option value="B">B</option>
</select>
<input type="submit" value="Next" />
</form>
</div>
My WebView2 can load about HTMLpage. I could not find any way when the user clicks on submit button how to get field_name
and listvalue
values?
Could you please give a pointer for the above problem?
CodePudding user response:
It is just WebView2 C equivalent code of the javascript-based answer.
webviewWindow->add_NavigationCompleted(Callback<ICoreWebView2NavigationCompletedEventHandler>(
[](ICoreWebView2* webview, ICoreWebView2NavigationCompletedEventArgs* args) -> HRESULT
{
webview->ExecuteScript(L"f = document.getElementById('submitButton');\
f.addEventListener('click', () => {\
const fieldNameInputValue = document.getElementById('field_name').value;\
const listValue = document.getElementById('listvalue');\
const listValueSelectionValue = listValue.options[listValue.selectedIndex].value;\
const result = { fieldNameInputValue, listValueSelectionValue };\
window.chrome.webview.postMessage(result);})"
, Callback<ICoreWebView2ExecuteScriptCompletedHandler>(
[](HRESULT errorCode, LPCWSTR resultObjectAsJson) -> HRESULT
{
return S_OK;
}).Get());
return S_OK;
}).Get(), &token);
HRESULT hr = webviewWindow->add_WebMessageReceived(Callback<ICoreWebView2WebMessageReceivedEventHandler>(
[hWnd](ICoreWebView2* webview, ICoreWebView2WebMessageReceivedEventArgs* args) -> HRESULT {
PWSTR message;
args->get_WebMessageAsJson(&message);
// processMessage(&message);
CoTaskMemFree(message);
return S_OK;
}).Get(), &token);
This code is based on MS sample code.
CodePudding user response:
You can use CoreWebView2.WebMessageReceived
to have script in the HTML document post messages to your hosting application. You could add script like the following
https://jsfiddle.net/3uqto6c0/
document.getElementById("submitButton").addEventListener("click", () => {
const fieldNameInputValue = document.getElementById("field_name").value;
const listValue = document.getElementById("listvalue");
const listValueSelectionValue = listValue.options[listValue.selectedIndex].value;
const result = {fieldNameInputValue, listValueSelectionValue};
console.log(JSON.stringify(result));
if (window?.chrome?.webview) {
// This will post the message to the WebView2's hosting application.
// See https://docs.microsoft.com/en-us/microsoft-edge/webview2/reference/win32/icorewebview2#add_webmessagereceived
window.chrome.webview.postMessage(result);
} else {
console.log("Not running in WebView2.");
}
});