IOS开发wkwebview与HTML页面JS互相交互的干货

由于IOS开发中需要引入html作为模板使用,与HTML中的JS进行互相传值交互,实现互通的功能。基本代码如下。

初始化设置代码

// WKWebView的配置
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
// js配置
config.userContentController = [[WKUserContentController alloc]init];
[config.userContentController addScriptMessageHandler:self name:@”getErrorPaperInfo”];

// 显示WKWebView
_webV = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) configuration:config];
_webV.allowsBackForwardNavigationGestures = YES;
// 代理
_webV.navigationDelegate = self;
_webV.scrollView.delegate = self;
[self addSubview:_webV];

// 加载本地html文件
NSString *filePath = [[NSBundle mainBundle] pathForResource:@”merrorpaper” ofType:@”html”];
NSURL *pathURL = [NSURL fileURLWithPath:filePath];
[_webV loadRequest:[NSURLRequest requestWithURL:pathURL]];

//WKScriptMessageHandler协议方法 监听JS调用ios方法
– (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
//code message.name 方法名 message.body 回调值
if ([message.name isEqualToString:@”getErrorPaperInfo”]) {
NSString *error_id = message.body;
}
}
//IOS调用JS的方法
– (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
[_webV evaluateJavaScript:[NSString stringWithFormat:@”javascript:setErrorPage(‘%@’)”,str] completionHandler:nil];

}

HTML代码

window.webkit.messageHandlers.getErrorPaperInfo.postMessage(‘{{id}}’)     window.webkit.messageHandlers.[方法名].postMessage([参数])

iso调用js方法 方法名(参数) getErrorPaperInfo([参数])

3人评论了“IOS开发wkwebview与HTML页面JS互相交互的干货”

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部