总结交互:交互一:利用超链接拦截URL方式传值
交互二:利用系统自带库javascriptCore传值
交互三:利用WKWebView拦截URL方式传值
交互四:利用WebViewJavascriptBridge传值
交互五:利用Cordova传值
一.利用UIWebView代理方法拦截URL的方式
//OC调用JS代码
NSString *result = [self.webView stringByEvaluatingJavaScriptFromString:@"showAlert('HELLO')"];
//JS调用OC代码
#pragma mark - UIWebViewDelegate
// 加载所有请求数据,以及控制是否加载
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
// request : host + 路由 : 拦截
if ([request.URL.scheme isEqualToString:@"tzedu"]) {
NSArray *paths = request.URL.pathComponents;
NSString *routerName = request.URL.host;
SEL methodSEL = NSSelectorFromString(routerName);
if ([self respondsToSelector:methodSEL]) {
// objc_msgSend(self,methodSEL,@"1234");
[self performSelector:methodSEL withObject:nil afterDelay:0];
}else{
NSLog(@"没有相应路由");
}
return NO;
}
return YES;
};
- (void)getPlus{
NSString *result = [self.webView stringByEvaluatingJavaScriptFromString:@"showAlert('HELLO')"];
NSLog(@"result == %@",result);
}
//js代码如下
<body>
<a href="tzedu://getSum:/helloword/js">点击跳转响应OC方法</a>
<a href="tzedu://getPlus/helloword/js">点击跳转响应</a>
<form id="myform" action="tzedu://www.baidu.com/hello/j/Users/cooci/Desktop/VIP/网络/网络第三天/02--代码/001---WebView初体验/001---WebView初体验/index.htmls" method="get">
<input id="submit" type="submit" value="我是提交">
</form>
<input type="button" value="弹框" οnclick="showAlert('hello JS')"><br/>
</body>
二.利用系统自带的JavaScriptCore实现交互
// OC调用JS代码
案例一
[self.jsContext evaluateScript:@"submit()"];
JS代码如下:
<script>
function submit(){
alert('submit');
}
</script>
//案例二
JSValue *jsFun = self.jsContext[@"testJS"];
//异步主线程执行js方法
dispatch_async(dispatch_get_main_queue(), ^{
//使用js的window.setTimeout方法执行需要调用的方法
[jsFun.context[@"setTimeout"] callWithArguments:@[jsFun, @0, @"江就红"]];
});
//js代码如下:
<script>
function testJS(arr){
alert("88888888" + arr);
}
</script>
//JS调用OC代码
jsContext[@"showMessage"] = ^{
NSArray *arr = [JSContext currentArguments];
NSLog(@"%@",arr);
};
//js代码如下:
<script>
function showAlert(){
showMessage("点击了弹框按钮...",arr);
}
</script>
三:利用WKWebView交互
//JS调用OC
#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
// 拦截 -- 超链接 -- 自定义
// if (路由) {
// NSLog(@"%@",navigationAction.request);
// decisionHandler(WKNavigationActionPolicyCancel);
}
decisionHandler(WKNavigationActionPolicyAllow);
}
//OC调用JS
NSString *jsStr2 = @"showAlert('messageHandle:OC-->JS')";
[self.webView evaluateJavaScript:jsStr2 completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSLog(@"%@----%@",result, error);
}];
]
//MessageHandler(OC调用JS同上)
//MessageHandler(js调用OC)
[self.webView.configuration.userContentController addScriptMessageHandler:self name:@"messgaeOC"];
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
NSLog(@"%@---%@",message.name,message.body);
// 展示不出来 -- 会打开 : iframe
// if (message.name) {
// <#statements#>
// }
}
//JS代码如下
<script>
function showAlert(messgae){
alert('我是一个可爱的弹框 \n'+messgae+'\n'+arr[1]);
return "token";
}
function messgaeHandle(){
// ANDROID
window.webkit.messageHandlers.messgaeOC.postMessage("Cooci 消息");
}
</script>
四:利用WebViewJavascriptBridge
//WKwebView的写法
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
WKUserContentController *wkUController = [[WKUserContentController alloc] init];
[wkUController addUserScript:wkUScript];
configuration.userContentController = wkUController;
self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration];
self.webView.UIDelegate = self;
[self.view addSubview:self.webView];
NSString *urlStr = [[NSBundle mainBundle] pathForResource:@"index.html" ofType:nil];
NSURL *fileURL = [NSURL fileURLWithPath:urlStr];
[self.webView loadFileURL:fileURL allowingReadAccessToURL:fileURL];
//UIWebView写法
self.webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:self.webView];
NSURL *url = [[NSBundle mainBundle] URLForResource:@"index.html" withExtension:nil];;
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
[self.webView loadRequest:request];
self.wjb = [WebViewJavascriptBridge bridgeForWebView:self.webView];
// 如果你要在VC中实现 UIWebView的代理方法 就实现下面的代码(否则省略)
[self.wjb setWebViewDelegate:self];
// JS-->OC
self.wjb = [WebViewJavascriptBridge bridgeForWebView:self.webView];
[self.wjb setWebViewDelegate:self];
[self.wjb registerHandler:@"jsCallsOC" handler:^(id data, WVJBResponseCallback responseCallback) {
NSLog(@"%@---%@----%@",[NSThread currentThread],data,responseCallback);
}];
//OC调用JS代码
- (IBAction)didClickLeftAction:(id)sender {
[self.wjb callHandler:@"OCCallJSFunction" data:@"糊涂蛋" responseCallback:^(id responseData) {
NSLog(@"%@--%@",[NSThread currentThread],responseData);
}];
}
//js代码
<script>
setupWebViewJavascriptBridge(function(bridge) {
// JS 被调用的方法 OCCallJSFunction 定义的标识
bridge.registerHandler('OCCallJSFunction', function(data, responseCallback) {
alert('JS方法被调用:'+data);
responseCallback('js执行过了');
})
})
function showWBJ(){
WebViewJavascriptBridge.callHandler('jsCallsOC', {'jhh': '18'}, function(response) {
alert(response);
})
}
</script>
五:利用Cordova交互
此处暂未深入了解,敬请期待!
//此处为学习截图:(辅助代码学习)