js代码:
/**
* js内部调用方法
* name:对应ios massage.name字段
* params:传参
* callback:原生内部回调js方法
*/
function CallApp(name, params, callback) {
if (params == null) {
params = {}
}
let data = {
name: name,
params: params,
callback: null
};
if (callback != null) {
var callback_name = 'C' + Math.random().toString(36).substr(2);
window[callback_name] = function(obj) {
callback(obj);
delete window[callback_name]
};
data.callback = callback_name
}
//alert(JSON.stringify(data))// alert方便调试 window.webkit.messageHandlers.call.postMessage(JSON.stringify(data));
};
CallApp('testAction', {
name: "name",
value: "value"
}, function(data) {
console.log(data);
});
ios代码:
1、设置self.webView.configuration.userContentController,注册方法名
WKUserContentController *userCC = self.webView.configuration.userContentController;
[userCC addScriptMessageHandler:self name:@"call"];
2、遵守协议WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
//筛选注册方法
if ([message.name isEqualToString:@"call"]) {
NSString *messageJson = [NSString stringWithFormat:@"%@", message.body];
NSData *data = [messageJson dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//获取回调的js方法名
NSString *callBack = jsonDict[@"callback"];
//success为测试参数,可以替换为其他的参数,实现原生向js传参
NSString *callBackString = [NSString stringWithFormat:@"%@('success')", callBack];
//通过wkwebview在网页的js环境中执行js代码
[self.webView evaluateJavaScript:callBackString completionHandler:^(id _Nullable obj, NSError * _Nullable error) {
NSLog(@"-- %@ %@", obj, error);
}];
}
}
3、移除注册方法
-(void)removeAllScriptMsgHandle{
WKUserContentController *controller = self.webView.configuration.userContentController;
[controller removeScriptMessageHandlerForName:@"call"];
}
赠人玫瑰手留余香,描述不准确之处,欢迎指出。共同学习,共同进步。谢谢。
网友评论