// 1.WKWebView的配置
WKUserContentController *userContentController = [[WKUserContentController alloc] init];
[userContentController addScriptMessageHandler:self name:@"myName"];
_wkConfig = [[WKWebViewConfiguration alloc] init];
_wkConfig.userContentController = userContentController;
_wkwebView = [[WKWebViewalloc] initWithFrame:self.view.boundsconfiguration:_wkConfig];
// 2.iOS 8 引入WKWebView, WKWebView 不支持JavaScriptCore的方式但提供message handler的方式为JavaScript 与Objective-C 通信.
在Objective-C 中使用WKWebView的以下方法调用JavaScript:
- (void)evaluateJavaScript:(NSString *)javaScriptString
completionHandler:(void (^)(id, NSError *))completionHandler
如果JavaScript 代码出错, 可以在completionHandler 进行处理.
[_wkwebView evaluateJavaScript:@"onPayComplete(1)" completionHandler:nil];// OC调用JS函数,可传参数
//3. WKScriptMessageHandler protocol?
- (void)userContentController:(WKUserContentController *)userContentController
didReceiveScriptMessage:(WKScriptMessage *)message
{
NSLog(@"Message: %@", message.body);
}
// 4.在JavaScript 将信息发给Objective-C:
// window.webkit.messageHandlers.<name>.postMessage();?
function postMyMessage()? {?
var message = { 'message' : 'Hello, World!', 'numbers' : [ 1, 2, 3 ] };?
window.webkit.messageHandlers.myName.postMessage(message);?
}