WKWebview - Complex communication between Javascript & native code

后端 未结 7 2068
渐次进展
渐次进展 2020-12-12 17:39

In WKWebView we can call ObjectiveC/swift code using webkit message handlers eg: webkit.messageHandlers..pushMessage(message)

It works we

7条回答
  •  温柔的废话
    2020-12-12 17:55

    I have a workaround for question1.

    PostMessage with JavaScript

    window.webkit.messageHandlers..postMessage(function(data){alert(data);}+"");
    

    Handle It in your Objective-C project

    -(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
        NSString *callBackString = message.body;
        callBackString = [@"(" stringByAppendingString:callBackString];
        callBackString = [callBackString stringByAppendingFormat:@")('%@');", @"Some RetString"];
        [message.webView evaluateJavaScript:callBackString completionHandler:^(id _Nullable obj, NSError * _Nullable error) {
            if (error) {
                NSLog(@"name = %@ error = %@",@"", error.localizedDescription);
            }
        }];
    }
    

提交回复
热议问题