wkwebView与js交互

还要写文章吗

JS核心代码

  • window.webkit.messageHandlers.JSCallOCMethod1.postMessage({"key1":"value1","key2":"value2"});

OC核心代码

OC暴露方法给JS, 供JS调用

    WKWebViewConfiguration *webConfig = [[WKWebViewConfiguration alloc] init];
    WKUserContentController *wkUserController = [[WKUserContentController alloc] init]; 
    NSArray *ocMeths = @[@"goDetail", @"goBack"];
    for (NSString *ocMethString in ocMeths) {
        [wkUController addScriptMessageHandler:self name:ocMethString];
    }
    webConfig.userContentController = wkUController;
    WKWebView *atWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 100, ScreenW, ScreenH-100) configuration:webConfig];

处理js调用, JS调用OC

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
   // 处理js的调用
NSLog(@"name:%@\\\\n body:%@\\\\n frameInfo:%@\\\\n",message.name,message.body,message.frameInfo);
}

你可能感兴趣的:(wkwebView与js交互)