iOS Question Receive data from webview

kohle

Active Member
Licensed User
Longtime User
Hi,
in a webview a website execute the following code :

JavaScript:
var data = localStorage.getItem("korgi-backup");
  webkit.messageHandlers.korgi.postMessage(data);

How can I receive this code in B4i (B4x)

Thanks
J.
 

b4x-de

Active Member
Licensed User
Longtime User
In B4i, you cannot retrieve the return value of a JavaScript function synchronously from a WebView. Instead, you use a callback-based mechanism. The standard and recommended way is to use `EvaluateJavaScript`, which is based on iOS’s WKWebView API.

You call your JavaScript function like this:

B4X:
WebView1.EvaluateJavaScript("myFunction();", Me, "JSResult")

Then implement the callback:

B4X:
Sub JSResult (Result As Object)
Log("JavaScript returned: " & Result)
End Sub

The value returned by the JavaScript function is passed to the "Result" parameter. It is important that the JavaScript function explicitly uses "return". Supported return types include simple values such as strings, numbers, and booleans. If you need to return more complex data (such as objects or arrays), convert them to a JSON string using JSON.stringify in JavaScript and parse them on the B4i side if necessary.

As an alternative, there is a custom URL scheme approach. In this method, JavaScript triggers a navigation to a special URL that B4i intercepts:

JavaScript:



B4i:

B4X:
Sub WebView1_OverrideURL(Url As String) As Boolean
If Url.StartsWith("b4i://") Then
Log(Url)
Return False
End If
Return True
End Sub

This works by intercepting the attempted navigation and extracting the value from the URL. However, this approach is generally considered a workaround. It is less clean and less efficient than using "EvaluateJavaScript", and should mainly be used in edge cases where the callback mechanism is not sufficient.

In practice, "EvaluateJavaScript" with a callback is the preferred solution because it is more direct, avoids unnecessary navigation, and is designed specificalthis purpose.
 
Upvote 0
Top