oc调用js方法
evaluateJavaScript: completionHandler:
h5页面中有如下js方法
function sayHello(name){
let message = 'hello,'+name+'!!!'
alert(message)
console.log(message)
return message
}
在WKWebView中通过oc调用这个js方法:
-(void)runJSFunction{
NSString *name = @"tom";
NSString *jsFunctionStr = [NSString stringWithFormat:@"sayHello('%@');",name]; //@"sayHello('tom');"
[self.webView evaluateJavaScript:jsFunctionStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSLog(@"%@ - %@",result, [result class]); //打印结果:hello,tom!!! - __NSCFString
}];
}
js调用oc方法
假设 原生端向前端提供了一个方法名为ocTestFunction的方法, 前端与原生端的通信过程如下.
原生端
// handler 为实现了 WKScriptMessageHandler协议的对象
ScriptMessageHandler *handler = [ScriptMessageHandler new];
[self.webView.configuration.userContentController addScriptMessageHandler:handler name: ocTestFunction];
注意需要在浏览器释放时移除WKScriptMessageHandler
-(void)dealloc{
// 移除js交互引用
[self.webView.configuration.userContentController removeScriptMessageHandlerForName:ocTestFunction];
}
前端js调用的格式:
window.webkit.messageHandlers.nativeFunctionName.postMessage
function jsToOcWithPrams(message) {
window.webkit.messageHandlers.ocTestFunction.postMessage({
body:{
"func" : "sayHello",
"data" : {"message" : message}
}
})
}
实现了 WKScriptMessageHandler协议的对象需要实现以下方法:
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message;
-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
//jsToOcNoPrams/jsToOcWithPrams
// message.name message.body
NSLog(@"name:%@\n body:%@\n frameInfo:%@\n",message.name,message.body,message.frameInfo);
//用message.body获得JS传出的参数体
NSDictionary *parameter = message.body;
NSString *functionName = parameter[@"func"];
NSDictionary *functionPrams = parameter[@"data"];
if ([functionName isEqualToString:@"sayHello"]) {
[self alertMessage:[NSString stringWithFormat:@"hello, %@",functionPrams[@"message"]]];
}
}
js注入
在webview初始化时, 向webView注入一个js方法, 这样前端页面都可以访问这个js方法了
NSString *jSString = @"function testFunction() { console.log('hello 2'); alert('this si test function'); }";
WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
[config.userContentController addUserScript:wkUScript];
网友评论