1.初始化一个WKWebview(viewdidload)
CGRect frame = self.view.frame;
frame.size.height -= 64;
WKWebViewConfiguration *congif = [WKWebViewConfiguration new];
congif.preferences.javaScriptEnabled = YES;
congif.preferences.javaScriptCanOpenWindowsAutomatically = YES;
WKWebView *WebView = [[WKWebView alloc]initWithFrame:frame configuration:congif];
WebView.navigationDelegate = self;
WebView.UIDelegate = self;
[self.view addSubview:WebView];
self.webView = WebView;
[self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
2. 将此WKWebview与WKWebViewJavascriptBridge关联(viewdidload)
if (_bridge) {
return;
}
//[WKWebViewJavascriptBridge enableLogging];
_bridge = [WKWebViewJavascriptBridge bridgeForWebView:WebView];
[_bridge setWebViewDelegate:self];
3. js调oc方法(可以通过data给oc方法传值,使用responseCallback将值再返回给js)
[_bridge registerHandler:@"testObjcCallback" handler:^(id data, WVJBResponseCallback responseCallback) {
NSLog(@"testObjcCallback called: %@", data);
responseCallback(@"Response from testObjcCallback");
}];
网页有触发事件后,才会调用括号里的方法。
这里注意testObjcCallback这个方法的标示。html那边的命名要跟ios这边相同,才能调到这个方法。当然这个名字可以两边商量着自定义。简单明确即可。
4.oc调js方法(通过data可以传值,通过 response可以接受js那边的返回值 )
id data = @{ @"greetingFromObjC": @"Hi there, JS!" };
[_bridge callHandler:@"testJavascriptHandler" data:data responseCallback:^(id response) {
NSLog(@"testJavascriptHandler responded: %@", response);
}];
注意这里的 testJavascriptHandler也是个方法标示。
5.oc给js传值(通过 response接受返回值 )
[_bridge send:@"A string sent from ObjC to JS" responseCallback:^(id response) {
NSLog(@"sendMessage got response: %@", response);
}];
6.oc给js传值(无返回值)
[_bridge send:@"A string sent from ObjC after Webview has loaded."];