I am working on an application where I need to call a WebMessageReceived event of WebView2 from the web page deployed but it is not working. below is the code for WebView2 and Front_End application.
Private Async Sub Form_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Try
Me.Cursor = Cursors.WaitCursor
Await wvGravityPayment.EnsureCoreWebView2Async
Dim url = String.Format("https://ba63-203-215-162-154.ngrok-free.app/?transactionToken={0}", mTransactionToken)
If Not String.IsNullOrEmpty(url) Then
wvGravityPayment.CoreWebView2.Navigate(url)
End If
AddHandler wvGravityPayment.WebMessageReceived, AddressOf wvGravityPayment_WebMessageReceived
Catch ex As Exception
ShowException(My.Resources.MsgCantPopulateForm, ex)
Finally
Me.Cursor = Cursors.Default
End Try
End Sub
Private Sub wvGravityPayment_WebMessageReceived(sender As Object, e As CoreWebView2WebMessageReceivedEventArgs) Handles wvGravityPayment.WebMessageReceived
Dim jsonData As String = e.WebMessageAsJson()
End Sub
Javascript Code
<script>
var iframe = document.createElement("iframe");
iframe.id = 'cip-hosted-urlpage';
iframe.style.display = 'none';
iframe.classList.add("iframeStyles");
$("#iframeDiv").append(iframe);
window.onload = function() {
// set up event listener on Pay With Card button
function StartTransaction () {
//e.preventDefault();
// get a transactionToken serverside
//getToken().then(function (transactionToken) {
//initialize the emergepay url library.
var transToken = getUrlVars()["transactionToken"];
debugger
var urlPage = emergepayUrlPage.init({
// (optional) Callback function that gets called after a successful transaction
onTransactionSuccess: function (approvalData) {
console.log("Approval Data", approvalData);
postCallbackResponse("true", approvalData);
//$(".iframeContainer").hide();
},
// (optional) Callback function that gets called after a failure occurs during the transaction (such as a declined card)
onTransactionFailure: function (failureData) {
console.log("Failure Data", failureData);
postCallbackResponse("false", failureData);
}
});
// set the source of the iframe to the emergepay page.
iframe.src = urlPage.getUrl(transToken);
iframe.style.display = 'block';
$(".iframeContainer").show();
//});
}
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
// Post response message from Callback function
function postCallbackResponse(approved, callbackResponse)
{
window.chrome.webview.postMessage(JSON.parse({isApproved: approved, transactionResponse: callbackResponse}));
}
StartTransaction();
}
</script>