Private Sub B4XPage_Created (Root1 As B4XView)
Root = Root1
Root.LoadLayout("MainPage")
Dim conf As NativeObject
conf = conf.Initialize("WKWebViewConfiguration").RunMethod("new", Null)
Dim NativeMe As NativeObject = Me
conf = NativeMe.RunMethod("getconfig:", Array(conf))
' With this line, JSCallback works but the page is not displayed (although PageFinished fires with the correct URL and Success = True)
' Without this line, the page is displayed but JSCallback can't work
WebView1.InitializeWithCustomConfiguration("WebView1", conf)
WebView1.LoadUrl("https://get.webgl.org/")
'WebView1.LoadUrl("https://www.google.com/")
End Sub
Private Sub WebView1_PageFinished (Success As Boolean, Url As String)
Log("PageFinished: " & Success & " " & Url)
End Sub
Private Sub WebView1_OverrideUrl (Url As String) As Boolean
Log("OverrideUrl: " & Url)
Return False
End Sub
Private Sub WebView1_JSComplete (Success As Boolean, Result As String)
Log("JSComplete " & Success)
End Sub
Private Sub JSCallback(body As Object) 'ignore
Log("JSCallback: " & body)
End Sub
Private Sub Button1_Click
WebView1.EvaluateJavaScript("window.webkit.messageHandlers.callback.postMessage('postMessage successful " & DateTime.Now & "');")
End Sub
#If OBJC
#import <Foundation/Foundation.h>
- (WKWebViewConfiguration *) getconfig: ( WKWebViewConfiguration *)config
{
WKUserContentController* userController = [[WKUserContentController alloc]init];
[userController addScriptMessageHandler:self name:@"callback"];
config.userContentController = userController;
return config;
}
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
if ([message.name isEqualToString:@"callback"]) {
[self.bi raiseEvent:nil event:@"jscallback:"params:@[message.body]];
}
}
#End If