一、本地代码所需操作
1、创建viewController并遵守协议
@interface ViewController ()<WKNavigationDelegate,WKScriptMessageHandler,WKUIDelegate>
2、注册ScriptMessageHandler
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
[configuration.userContentController addScriptMessageHandler:self name:@"Redirect"];
self.secondWebView = [[[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuration] autorelease];
3、实现WKScriptMessageHandler协议的代理方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
NSLog(@"message====%@",message);
}
二、JavaScript代码
1、用WKWebView加载h5页面触发js代码如下
var message = native;
window.webkit.messageHandlers.Redirect.postMessage(message)
三、执行js代码之后,本地代理方法就会监听到js传过来的数据,控制台输出
message====native
总结:
1、swift实现流程:http://www.cocoachina.com/swift/20150907/13356.html
2、本地注册的ScriptMessageHandler与js里边window.webkit.messageHandlers.后边的名字要保持一致。
eg.
//这两句代码同为:Redirect
[configuration.userContentController addScriptMessageHandler:self name:@"Redirect"];
window.webkit.messageHandlers.Redirect.postMessage(message)