最近做的项目中涉及到很多的报表的展示页面是用H5做的,H5的强大也让我感到是时候要学学H5和JS了。感慨归感慨,由于原生和H5共同的存在项目中,必然涉及到原生和H5的交互。
无意中在某个帖子中发现了一个叫WebViewJavascriptBridge的第三方,然后查找资料总结了一下它的用法如下:
HTML文件中写入如下代码:
function setupWebViewJavascriptBridge(callback) { if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); } if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); } window.WVJBCallbacks = [callback]; var WVJBIframe = document.createElement('iframe'); WVJBIframe.style.display = 'none'; WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__'; document.documentElement.appendChild(WVJBIframe); setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0) } setupWebViewJavascriptBridge(function(bridge) { var uniqueId = 1 function log(message, data) { var log = document.getElementById('log') var el = document.createElement('div') el.className = 'logLine' el.innerHTML = uniqueId++ + '. ' + message + ':
' + JSON.stringify(data) if (log.children.length) { log.insertBefore(el, log.children[0]) } else { log.appendChild(el) } } bridge.registerHandler('testJavascriptHandler', function(data, responseCallback) { log('ObjC called testJavascriptHandler with', data) var responseData = { 'Javascript Says':'Right back atcha!' } log('JS responding with', responseData) responseCallback(responseData) }) document.body.appendChild(document.createElement('br')) var callbackButton = document.getElementById('buttons').appendChild(document.createElement('button')) callbackButton.innerHTML = 'Fire testObjcCallback' callbackButton.onclick = function(e) { e.preventDefault() log('JS calling handler "testObjcCallback"') bridge.callHandler('testObjcCallback', {'foo': 'bar'}, function(response) { log('JS got response', response) }) } })
native的用法,首先引入WebViewJavascriptBridge,然后具体用法如下:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self.view setBackgroundColor:[UIColor whiteColor]];
[self addUI];
[self loadHtmlFile];
}
- (void)viewWillAppear:(BOOL)animated{
if (_bridge) {
return;
}
[WebViewJavascriptBridge enableLogging];
_bridge=[WebViewJavascriptBridge bridgeForWebView:self.webView];
[_bridge registerHandler:@"testObjcCallback" handler:^(id data, WVJBResponseCallback responseCallback) {
NSLog(@"testOcCallBack called:%@",data);
responseCallback(@"response from testOCCallBack");
}];
[_bridge callHandler:@"testJavascriptHandler" data:@{@"foo":@"before ready"}];
}
-(void)addUI{
self.webView.frame=CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height*0.7);
self.commitBtn.frame=CGRectMake(0, CGRectGetMaxY(_webView.frame)+50, [UIScreen mainScreen].bounds.size.width, 50);
[self.view addSubview:self.webView];
[self.view addSubview:self.commitBtn];
}
- (UIWebView *)webView{
if (!_webView) {
_webView=[[UIWebView alloc]init];
}
return _webView;
}
- (UIButton *)commitBtn{
if (!_commitBtn) {
_commitBtn=[UIButton buttonWithType:UIButtonTypeSystem];
[_commitBtn setTitle:@"commit" forState:UIControlStateNormal];
[_commitBtn addTarget:self action:@selector(commitBtnAction:) forControlEvents:UIControlEventTouchUpInside];
}
return _commitBtn;
}
-(void)loadHtmlFile{
NSString* htmlPath = [[NSBundle mainBundle] pathForResource:@"testApp" ofType:@"html"];
NSString* appHtml = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];
NSURL *baseURL = [NSURL fileURLWithPath:htmlPath];
[self.webView loadHTMLString:appHtml baseURL:baseURL];
}
#pragma mark -commit Action
-(void)commitBtnAction:(UIButton *)btn{
id data=@{@"greetingFromObjc": @" hi i'm zhangxinxin's js !"};
[_bridge callHandler:@"testJavascriptHandler" data:data responseCallback:^(id responseData) {
NSLog(@"testJavascriptHandler responded : %@",responseData);
}];
}
由此就可以实现webView和网页js的交互了。