webview与js交互方式,调用js方法要在Obj-C中写js代码,这种方式非常臃肿,耦合性强。 WebViewJavascriptBridge框架就完美解决了webview的这缺点。
WebViewJavascriptBridge的原理也是通过webview的stringByEvaluatingJavaScriptFromString:方法调用JavaScript代码;JavaScript调用Obj-C,则是通过web view的代理方法shouldStartLoadWithRequest:来接收JavaScript的网络请求从而实现调用。
[WebViewJavascriptBridge下载地址](https://github.com/marcuswestin/WebViewJavascriptBridge)
**WebViewJavascriptBridge的使用:**
1、把WebViewJavascriptBridge文件夹导入到项目中。
2、引入头文件和声明属性。
~~~
#import "WebViewJavascriptBridge.h"
...
@property WebViewJavascriptBridge* bridge;
~~~
3、Obj-C和javascript实例化
3.1、实例化WebViewJavascriptBridge。javascript发送的消息都在此处接收。
~~~
//初始化WebViewJavascriptBridge
_bridge = [WebViewJavascriptBridge bridgeForWebView:webView handler:^(id data, WVJBResponseCallback responseCallback) {
NSLog(@"接收从javascript发送过来的信息: %@", data);//接受从js传过来的值
responseCallback(@"oc影响信息"); //相应消息,发送到js
}];
~~~
3.2 、javascript要和Obj-C交换,html/jsp 页面必须要声明方法并注册WebViewJavascriptBridgeReady监听。以下javascript代码是固定写法:
~~~
function connectWebViewJavascriptBridge(callback) {
if (window.WebViewJavascriptBridge) {
callback(WebViewJavascriptBridge);
} else {
document.addEventListener('WebViewJavascriptBridgeReady', function() {
callback(WebViewJavascriptBridge);
}, false);
}
}
connectWebViewJavascriptBridge(function(bridge) {
//.....此处写和oc交换的js代码
});
~~~
3.3、javascript初始化WebViewJavascriptBridge. 这会调起 ‘WebViewJavascriptBridgeReady’ 的事件handler.Obj-C发送的消息都在此处接收。
~~~
connectWebViewJavascriptBridge(function(bridge) {
/* <span style="color: rgb(37, 37, 37); font-family: Monaco; font-size: 11px;">初始化 </span>Init your app here */
bridge.init(function(message, responseCallback) {
alert("Javascript 接收从oc发送过来的信息: " + message);
if (responseCallback) {
responseCallback("javascript 响应信息")
}
});
});
~~~
4、发送消息
4.1、Obj-C发送消息给javascript。
~~~
//发送消息给javascript
[_bridge send:@"OC发送一条信息给javascript"];
~~~
4.2、javascript发送消息给Obj-c。
~~~
bridge.send("javascript发送一条信息给OC");
~~~
5、Obj-c调用javascript。
5.1、javascript注册handler(用于被Obj-c获取该handler调用)
~~~
//注册一个叫做 testJavascriptHandler 的handler(用于被oc获取该handler调用)
//data:接受oc传的数据 responseCallback:相应后返回的数据
bridge.registerHandler("testJavascriptHandler", function(data, responseCallback) {
alert("ObjC called testJavascriptHandler with:"+data);
var responseData = { 'Javascript Says':'Javascript已响应!' }
responseCallback(responseData)
});
~~~
5.2、Obj-c调用javascript代码。
~~~
//调用javascript叫做 testJavascriptHandler的handler. 在调用 handler成功后可以通过responseCallback block做出反应.
[_bridge callHandler:@"testJavascriptHandler" data:@"我是oc传过来的" responseCallback:^(id responseData) {
//responseData :Javascript相应后返回的消息
NSLog(@"jJavascript Says:%@",responseData[@"Javascript Says"]);
}];
~~~
6、javascript调用Obj-c
6.1、Obj-c注册handler(用于被javascript获取该handler调用)
~~~
//注册一个叫做 testOCHandler 的handler
[_bridge registerHandler:@"testOCHandler" handler:^(id data, WVJBResponseCallback responseCallback) {
NSLog(@"testObjcCallback called: %@", data);
responseCallback(@"Response from testOCCallback:oc已响应!");
}];
~~~
6.2、javascript调用Obj-c代码。
~~~
//调用oc叫做 testOCHandler的handler
bridge.callHandler("testOCHandler","我是javascript传过来的",function(response){
//response:oc响应后返回的数据
alert("oc响应后返回的数据:"+response);
});
~~~
完整的Obj-c代码
~~~
//
// ViewController.m
// WebViewJavascriptBridge
//
#import "ViewController.h"
#import "WebViewJavascriptBridge.h"
@interface ViewController ()
@property WebViewJavascriptBridge *bridge;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIWebView *webView = [[UIWebView alloc] init];
webView.frame = self.view.frame;
[self.view addSubview:webView];
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/test/index.jsp"];
NSURLRequest *rquest = [NSURLRequest requestWithURL:url];
[webView loadRequest:rquest];
//初始化WebViewJavascriptBridge
_bridge = [WebViewJavascriptBridge bridgeForWebView:webView handler:^(id data, WVJBResponseCallback responseCallback) {
NSLog(@"接收从javascript发送过来的信息: %@", data);//接受从js传过来的值
responseCallback(@"oc影响信息"); //相应消息,发送到js
}];
//发送消息给javascript
[_bridge send:@"OC发送一条信息给javascript"];
//注册一个叫做 testOCHandler 的handler
[_bridge registerHandler:@"testOCHandler" handler:^(id data, WVJBResponseCallback responseCallback) {
NSLog(@"testObjcCallback called: %@", data);
responseCallback(@"Response from testOCCallback:oc已响应!");
}];
//调用javascript叫做 testJavascriptHandler的handler. 在调用 handler成功后可以通过responseCallback block做出反应.
[_bridge callHandler:@"testJavascriptHandler" data:@"我是oc传过来的" responseCallback:^(id responseData) {
//responseData :Javascript相应后返回的消息
NSLog(@"jJavascript Says:%@",responseData[@"Javascript Says"]);
}];
}
@end
~~~
完整的jsp页面代码
~~~
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<script type="text/javascript">
function connectWebViewJavascriptBridge(callback) {
if (window.WebViewJavascriptBridge) {
callback(WebViewJavascriptBridge);
} else {
document.addEventListener('WebViewJavascriptBridgeReady', function() {
callback(WebViewJavascriptBridge);
}, false);
}
}
connectWebViewJavascriptBridge(function(bridge) {
/* Init your app here */
bridge.init(function(message, responseCallback) {
alert("Javascript 接收从oc发送过来的信息: " + message);
if (responseCallback) {
responseCallback("javascript 响应信息")
}
});
var sendMessage = document.getElementById("sendMessage");
sendMessage.onclick = function(e){
bridge.send("javascript发送一条信息给OC");
}
bridge.send("Please respond to this", function responseCallback(responseData) {
//console.log("Javascript got its response", responseData)
alert("Javascript 获取响应信息"+ responseData);
})
//注册一个叫做 testJavascriptHandler 的handler(用于被oc获取该handler调用)
//data:接受oc传的数据 responseCallback:相应后返回的数据
bridge.registerHandler("testJavascriptHandler", function(data, responseCallback) {
alert("ObjC called testJavascriptHandler with:"+data);
var responseData = { 'Javascript Says':'Javascript已响应!' }
responseCallback(responseData)
});
var callbackButton = document.getElementById("buttons");
callbackButton.onclick = function(e){
e.preventDefault();
//调用oc叫做 testOCHandler的handler
bridge.callHandler("testOCHandler","我是javascript传过来的",function(response){
//response:oc响应后返回的数据
alert("oc响应后返回的数据:"+response);
});
}
});
</script>
<body>
<div id='buttons'>点击WKWebViewJavascriptBridge方法调用oc方法</div>
<div id='sendMessage'>点击WKWebViewJavascriptBridge发送消息给oc</div>
</body>
</html>
~~~
参考文章:[http://www.cocoachina.com/ios/20150629/12248.html](http://www.cocoachina.com/ios/20150629/12248.html)
[demo下载地址](http://download.csdn.net/detail/zhixinhuacom/9384749)
- 前言
- iOS开发实践之SQLite3
- iOS开发实践之FMDB
- Obj-C与javascript交互之WebViewJavascriptBridge
- iOS开发实践之UIWebView
- iOS开发实践之多线程(基本概念)
- iOS开发实践之多线程(NSThread)
- iOS开发实践之多线程(GCD)
- iOS开发实践之多线程(单例模式)
- iOS开发实践之xib加载注意问题
- iOS开发实践之多线程(NSOperation)
- iOS开发实践之cell下载图片(NSOperation)
- iOS开发实践之cell下载图片(自定义NSOperation)
- iOS开发实践之cell下载图片(SDWebImage)
- iOS开发实践之JSON
- iOS开发实践之XML
- iOS开发实践之GET和POST请求
- iOS开发实践之网络检测Reachability
- iOS开发实践之MD5加密