JS 调用 OC
oc部分
//这个类主要用来做native与JavaScript的交互管理 WKUserContentController * wkUController = [[WKUserContentController alloc] init]; //注册一个name为jsToOcNoPrams的js方法 设置处理接收JS方法的对象 [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"jsToOcNoPrams"]; [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:@"jsToOcWithPrams"];
-
设置代理并且导入代理
<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler> self.webView.UIDelegate = self; self.webView.navigationDelegate = self;
-
在代理方法里实现
- (void)userContentController:(WKUserContentController*)userContentController didReceiveScriptMessage:(WKScriptMessage*)message;
- (void)userContentController:(WKUserContentController*)userContentController didReceiveScriptMessage:(WKScriptMessage*)message { NSLog(@"name:%@\\\\n body:%@\\\\n frameInfo:%@\\\\n",message.name,message.body,message.frameInfo); //用message.body获得JS传出的参数体 NSDictionary * parameter = message.body; //JS调用OC if([message.name isEqualToString:@"jsToOcNoPrams"]){ UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"js调用到了oc" message:@"不带参数" preferredStyle:UIAlertControllerStyleAlert]; [alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { }])]; [self presentViewController:alertController animated:YES completion:nil]; }else if([message.name isEqualToString:@"jsToOcWithPrams"]){ UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"js调用到了oc" message:parameter[@"params"] preferredStyle:UIAlertControllerStyleAlert]; [alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { }])]; [self presentViewController:alertController animated:YES completion:nil]; } }
-
移出监听
- (void)dealloc{ //移除注册的js方法 [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"jsToOcNoPrams"]; [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"jsToOcWithPrams"]; //移除观察者 [_webView removeObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress))]; [_webView removeObserver:self forKeyPath:NSStringFromSelector(@selector(title))]; }
js部分
<body>
<p style="text-align:center"> <button id="btn1" type = "button" onclick = "jsToOcFunction1()" > JS调用OC:不带参数 </button> </p>
<script type = "text/javascript">
function jsToOcFunction1()
{
window.webkit.messageHandlers.jsToOcNoPrams.postMessage({});
}
function jsToOcFunction2()
{
window.webkit.messageHandlers.jsToOcWithPrams.postMessage({"params":"我是参数"});
}
</script>
</body>
oc调用js
oc部分
js 跟 oc 端协议好方法名 比如 js 的方法为 transferPrama(str)
//oc 在合适的时机调用 js 方法(可以传参数)
//OC调用JS
- (void)ocToJs{
//changeColor()是JS方法名,completionHandler是异步回调block
NSString *jsString = [NSString stringWithFormat:@"changeColor('%@')", @"Js颜色参数"];
[_webView evaluateJavaScript:jsString completionHandler:^(id _Nullable data, NSError * _Nullable error) {
NSLog(@"改变HTML的背景色");
}];
//改变字体大小 调用原生JS方法
NSString *jsFont = [NSString stringWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%d%%'", arc4random()%99 + 100];
[_webView evaluateJavaScript:jsFont completionHandler:nil];
//
NSString * path = [[NSBundle mainBundle] pathForResource:@"girl" ofType:@"png"];
NSString *jsPicture = [NSString stringWithFormat:@"changePicture('%@','%@')", @"pictureId",path];
[_webView evaluateJavaScript:jsPicture completionHandler:^(id _Nullable data, NSError * _Nullable error) {
NSLog(@"切换本地头像");
}];
NSString *jsStr = [NSString stringWithFormat:@"alert('啦啦')"];
[_webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable data, NSError * _Nullable error) {
NSLog(@"ccjs");
}];
}
js部分
//OC调用JS改变背景色
function changeColor(parameter)
{
document.body.style.backgroundColor = randomColor();
<!-- alert(parameter);-->
}
//随机生成颜色
function randomColor()
{
var r=Math.floor(Math.random()*256);
var g=Math.floor(Math.random()*256);
var b=Math.floor(Math.random()*256);
return "rgb("+r+','+g+','+b+")";//所有方法的拼接都可以用ES6新特性`其他字符串{$变量名}`替换
}
// 切换图片
function changePicture(id, path) {
var image = document.getElementById(id);
image.src = path;
}
总结
总结
JS 调用 OC 走的是监听回调
\- (void)userContentController:(WKUserContentController*)userContentController didReceiveScriptMessage:(WKScriptMessage*)message
OC 调用 JS 走的是JS方法调用
\- (void)evaluateJavaScript:(NSString*)javaScriptString completionHandler:(void(^_Nullable)(_Nullableid,NSError*_Nullableerror))completionHandler;
网友评论