基于wkwebview的和JS 交互
遵守两个协议
<WKNavigationDelegate,WKScriptMessageHandler>
WKWebViewConfiguration * configuration = [[WKWebViewConfiguration alloc]init];
userContentController =[[WKUserContentController alloc]init];
configuration.userContentController = userContentController;
self=[super initWithFrame:CGRectZero configuration:configuration];
//注册
[userContentController addScriptMessageHandler:self name:@"cleanCatch"];
[userContentController addScriptMessageHandler:self name:@"testOcFun"];
由于和Js交互会导致内存泄漏,所以dealloc remove掉
-(void)dealloc{
//这里需要注意,前面增加过的方法一定要remove掉。
[userContentController removeScriptMessageHandlerForName:@"cleanCatch"];
[userContentController removeScriptMessageHandlerForName:@"testOcFun"];
}
JS 调用OC
//代理函数
-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
//window.webkit.messageHandlers.<message.name>.postMessage(<message.body>);
NSLog(@"JS 调用OC");
NSLog(@"%@,%@",message.name,message.body);
if([message.name isEqualToString:@"cleanCatch"]){
//清缓存
[self cleanCatcheAction];
}else if([message.name isEqualToString:@"testOcFun"]){
//测试
[self test];
}
}
OC 调用JS 函数
-(void)test{
//调用方式: JS函数名(字符串参数)
[self ocUseJsFunctionParms:@"OcCallJsfun2(\"{"ret":"success"}\")"];
}
//OC调用Js
-(void)ocUseJsFunctionParms:(NSString*)parms{
//@"方法名(\"参数\")" demo: NSString *jsStr = [NSString stringWithFormat:@"shareResult('%@','%@','%@')",title,content,url];
NSLog(@"OC 调用 JS");
//NSString*jsstr = [NSString stringWithFormat:@"cleanCatchFinish(\"%@\")",parms];
dispatch_async(dispatch_get_main_queue(), ^{
//OC 调用 JS
[self evaluateJavaScript:parms completionHandler:^(id _Nullable result, NSError * _Nullable error) {
if (error) {
NSLog(@"出错:%@",error);
}else{
NSLog(@"OC 调用JS 成功");
}
}];
});
}
HTML网页,我是加载本地的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<script type="text/javascript" src="jquery-3.2.0.min.js"></script>
<script type="text/javascript">
function JsCallOC1() {
window.webkit.messageHandlers.cleanCatch.postMessage(null);
}
function JsCallOC2() {
window.webkit.messageHandlers.testOcFun.postMessage(null);
}
function OcCallJsfun2(parmss) {
document.write("<p>"+JSON.stringify(parmss)+"</p>");
}
function OcCallJsfun1() {
alert('调用无参数的JS方法');
}
</script>
<style type="text/css">
#a{
color:red;
}
</style>
<body bgcolor="aqua">
<button type="button" onclick="JsCallOC1()">调用无惨函数</button>
<button type="button" onclick="JsCallOC2()">调用有参数函数</button>
<a type="button" onclick="JsCallOC3()"id="tel">10086</a>
</body>
</html>