1.UIWebView js編碼是window.prompt()
2.WKWebVIew js編碼window.webkit.messageHandlers.(name).postMessage()
iOS13棄用UIWebView。換成WKWebVIew狂秦,js編碼方法更改养涮。之前用的JavaScriptCore (JSContext)已不能用,為了保證安卓端和H5端不更改項(xiàng)目源碼竞穷,兼容老版本,采取了腳本轉(zhuǎn)換的方法鳞溉。
1.注入本地js腳本, 使js和native交互方法統(tǒng)一瘾带。
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回調(diào)統(tǒng)一處理熟菲。
// WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
NSLog(@"name:%@---body:%@",message.name,message.body);
//用message.body獲得JS傳出的參數(shù)體
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 = {};
//無返回值方法轉(zhuǎn)換
//會(huì)將jsCallNative.toLogin()的調(diào)用方式看政,轉(zhuǎn)換成window.webkit.messageHandlers.jsCallNative.postMessage()
jsCallNative.nativeClosePage = function () {
calliOSFunction("ShowSnappedUpObj","nativeClosePage");
}
//有返回值方法轉(zhuǎn)換
jsCallNative.nativeShowHud = function (infoStr) {
calliOSFunction("ShowSnappedUpObj","nativeShowHud",infoStr);
}
//有返回值方法轉(zhuǎn)換
//會(huì)將jsCallNative.getSign()的調(diào)用方式,轉(zhuǎn)換成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;