1.iOS给H5注入方法,例如给cookie注入多语言,给h5注入一个方法
//多语言
NSString *lang = [EXUserManager getCurrentLanguageCode];
WKUserScript * cookieScript = [[WKUserScript alloc] initWithSource:[NSString stringWithFormat:@"document.cookie = 'LANG=%@'",lang] injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
[userContentController addUserScript:cookieScript];
//注入token方法
NSString *script = [NSString stringWithFormat:@"window.setToken = function() { return {'token':'%@','token_expire':'%@'} }",[EXUserManager userInfo].token, [EXUserManager userInfo].token_expire];
WKUserScript *userScript = [[WKUserScript alloc] initWithSource:script injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
[userContentController addUserScript:userScript];
2.H5调用iOS的方法
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
[config.userContentController addScriptMessageHandler:self name:@"answerResult"];
- (void)userContentController:(WKUserContentController *)userContentController
didReceiveScriptMessage:(WKScriptMessage *)message {
NSString *messageStr = [NSString stringWithFormat:@"%@",message.body];
if ([message.name isEqualToString:@"answerResult"]) {
//写自己的方法
}
}
3.iOS 调用H5的方法
NSString *command = [NSString stringWithFormat:@"ToPage('%@');",page];
[self.classRoomView.webView evaluateJavaScript:command completionHandler:nil];