1.UIWebView js编码是window.prompt()
2.WKWebVIew js编码window.webkit.messageHandlers.(name).postMessage()
iOS13弃用UIWebView。换成WKWebVIew,js编码方法更改。之前用的JavaScriptCore (JSContext)已不能用,为了保证安卓端和H5端不更改项目源码,兼容老版本,采取了脚本转换的方法。
1.注入本地js脚本, 使js和native交互方法统一。
NSString *jsSource = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ios_brige" ofType:@"js"] encoding:NSUTF8StringEncoding error:nil];
WKUserScript *script = [[WKUserScript alloc] initWithSource:jsSource injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
[config.userContentController addUserScript:script];
2.WKScriptMessageHandler,JS回调统一处理。
// WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
NSLog(@"name:%@---body:%@",message.name,message.body);
//用message.body获得JS传出的参数体
NSString * parameter = message.body;
NSData *jsonData = [parameter dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
NSString *method = dic[@"method"];
NSString *param = dic[@"params"];
if (param) {
method = [method stringByAppendingString:@":"];
}
SEL sel = NSSelectorFromString(method);
if ([self respondsToSelector:sel]) {
[self performSelectorOnMainThread:sel withObject:param waitUntilDone:YES];
}else{
NSLog(@"webview not find method %@",method);
}
}
3.本地JS代码如下处理
function calliOSFunction(namespace, functionName, args, callback) {
if (!window.webkit.messageHandlers[namespace]) return;
var wrap = {
"method": functionName,
"params": args
};
window.webkit.messageHandlers[namespace].postMessage(JSON.stringify(wrap));
}
var jsCallNative = {};
//无返回值方法转换
//会将jsCallNative.toLogin()的调用方式,转换成window.webkit.messageHandlers.jsCallNative.postMessage()
jsCallNative.nativeClosePage = function () {
calliOSFunction("ShowSnappedUpObj","nativeClosePage");
}
//有返回值方法转换
jsCallNative.nativeShowHud = function (infoStr) {
calliOSFunction("ShowSnappedUpObj","nativeShowHud",infoStr);
}
//有返回值方法转换
//会将jsCallNative.getSign()的调用方式,转换成window.prompt()
jsCallNative.getSign = function () {
var result = window.prompt("getSign");
return result;
}
jsCallNative.appendABCwithString = function (str) {
var result = window.prompt("appendABCwithString",str);
return result;
}
jsCallNative.isLogin = function () {
var result = window.prompt("isLogin");
return result;
}
window["ShowSnappedUpObj"] = jsCallNative;