First, the local code needs to operate
1. Create Viewcontroller and comply with the agreement
@interface ViewController ()<WKNavigationDelegate,WKScriptMessageHandler,WKUIDelegate>
2, Registered Scriptmessagehandler
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];[configuration.userContentController addScriptMessageHandler:self name:@"Redirect"];self.secondWebView = [[[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuration] autorelease];
3, the implementation of Wkscriptmessagehandler protocol agent method
(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{ NSLog(@"message====%@",message);}
Second, JavaScript code
1, with Wkwebview load h5 page trigger JS code as follows
var message = native;window.webkit.messageHandlers.Redirect.postMessage(message)
Third, after the implementation of the JS code, the local agent method will be heard JS transmitted data, the console output
message====native
Summarize:
1, Swift implementation process: Http://www.cocoachina.com/swift/20150907/13356.html
2, the local registered Scriptmessagehandler and JS inside Window.webkit.messageHandlers. The name behind is to be consistent.
eg.//这两句代码同为:Redirect[configuration.userContentController addScriptMessageHandler:self name:@"Redirect"];window.webkit.messageHandlers.Redirect.postMessage(message)
Ios-javascript value to Wkwebview