iOS 开发 OC(wkwebview)与JS交互

JS传值给OC:

JS代码:window.webkit.messageHandlers.方法名.postMessage(参数)


OC代码

init方法中:

[self.wkWebView.configuration.userContentController addScriptMessageHandler:self name:@"方法名"];

代理方法:

#pragma mark - WKScriptMessageHandler

- (void)userContentController:(WKUserContentController*)userContentController didReceiveScriptMessage:(WKScriptMessage*)message

{

    if([message.name  isEqualToString:@"方法名"]) {

        if([kFormat(@"%@", message.body)isEqualToString:@"1"]){

             // message.body  传过来的值

        }

}



OC传值到JS

JS代码:

window["方法名"] = function(参数, 参数) {

}


OC代码:

代理方法:- (void)webView:(WKWebView*)webView didFinishNavigation:(WKNavigation*)navigation;

中写下面这个方法

[weakSelf.webView.wkWebView evaluateJavaScript:@"方法名('参数')"  completionHandler:^(id_Nullableresponse,NSError*_Nullableerror) {

            NSLog(@"error == %@",error);

        }];


你可能感兴趣的:(iOS 开发 OC(wkwebview)与JS交互)