iOS中html5的交互:WebViewJavascriptBridge
https://github.com/marcuswestin/WebViewJavascriptBridge
Setup & Examples (iOS & OSX)
Start with the Example Apps/ folder. Open either the iOS or OSX project and hit run to see it in action.
To use a WebViewJavascriptBridge in your own project:
1) Drag the WebViewJavascriptBridge
folder into your project.
- In the dialog that appears, uncheck "Copy items into destination group's folder" and select "Create groups for any folders"
2) Import the header file and declare an ivar property:
#import "WebViewJavascriptBridge.h"
...
@property WebViewJavascriptBridge* bridge;
3) Instantiate WebViewJavascriptBridge with a UIWebView (iOS) or WebView (OSX):
self.bridge = [WebViewJavascriptBridge bridgeForWebView:webView handler:^(id data, WVJBResponseCallback responseCallback) {
NSLog(@"Received message from javascript: %@", data);
responseCallback(@"Right back atcha");
}];
4) Go ahead and send some messages from ObjC to javascript:
[self.bridge send:@"Well hello there"];
[self.bridge send:[NSDictionary dictionaryWithObject:@"Foo" forKey:@"Bar"]];
[self.bridge send:@"Give me a response, will you?" responseCallback:^(id responseData) {
NSLog(@"ObjC got its response! %@", responseData);
}];
4) Finally, set up the javascript side:
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('Received message: ' + message)
if (responseCallback) {
responseCallback("Right back atcha")
}
})
bridge.send('Hello from the javascript')
bridge.send('Please respond to this', function responseCallback(responseData) {
console.log("Javascript got its response", responseData)
})
})
WKWebView Support (iOS 8 & OS 10.10)
WARNING: WKWebView still has many bugs and missing network APIs. It may not be a simple drop-in replacement.
WebViewJavascriptBridge supports WKWebView for iOS 8 and OSX Yosemite. In order to use WKWebView you need to instantiate the WKWebViewJavascriptBridge
. The rest of the WKWebViewJavascriptBridge
API is the same as WebViewJavascriptBridge
.
1) Import the header file:
#import "WKWebViewJavascriptBridge.h"
2) Instantiate WKWebViewJavascriptBridge and with a WKWebView object
WKWebViewJavascriptBridge* bridge = [WKWebViewJavascriptBridge bridgeForWebView:webView handler:^(id data, WVJBResponseCallback responseCallback) {
NSLog(@"Received message from javascript: %@", data);
responseCallback(@"Right back atcha");
}];
Contributors & Forks
Contributors: https://github.com/marcuswestin/WebViewJavascriptBridge/graphs/contributors
Forks: https://github.com/marcuswestin/WebViewJavascriptBridge/network/members
API Reference
ObjC API
[WebViewJavascriptBridge bridgeForWebView:(UIWebView/WebView*)webview handler:(WVJBHandler)handler]
[WebViewJavascriptBridge bridgeForWebView:(UIWebView/WebView*)webview webViewDelegate:(UIWebViewDelegate*)webViewDelegate handler:(WVJBHandler)handler]
Create a javascript bridge for the given web view.
The WVJBResponseCallback
will not be nil
if the javascript expects a response.
Optionally, pass in webViewDelegate:(UIWebViewDelegate*)webViewDelegate
if you need to respond to the web view's lifecycle events.
Example:
[WebViewJavascriptBridge bridgeForWebView:webView handler:^(id data, WVJBResponseCallback responseCallback) {
NSLog(@"Received message from javascript: %@", data);
if (responseCallback) {
responseCallback(@"Right back atcha");
}
}] [WebViewJavascriptBridge bridgeForWebView:webView webViewDelegate:self handler:^(id data, WVJBResponseCallback responseCallback) { /* ... */ }];
[bridge send:(id)data]
[bridge send:(id)data responseCallback:(WVJBResponseCallback)responseCallback]
Send a message to javascript. Optionally expect a response by giving a responseCallback
block.
Example:
[self.bridge send:@"Hi"];
[self.bridge send:[NSDictionary dictionaryWithObject:@"Foo" forKey:@"Bar"]];
[self.bridge send:@"I expect a response!" responseCallback:^(id responseData) {
NSLog(@"Got response! %@", responseData);
}];
[bridge registerHandler:(NSString*)handlerName handler:(WVJBHandler)handler]
Register a handler called handlerName
. The javascript can then call this handler with WebViewJavascriptBridge.callHandler("handlerName")
.
Example:
[self.bridge registerHandler:@"getScreenHeight" handler:^(id data, WVJBResponseCallback responseCallback) {
responseCallback([NSNumber numberWithInt:[UIScreen mainScreen].bounds.size.height]);
}];
[bridge callHandler:(NSString*)handlerName data:(id)data]
[bridge callHandler:(NSString*)handlerName data:(id)data responseCallback:(WVJBResponseCallback)callback]
Call the javascript handler called handlerName
. Optionally expect a response by giving a responseCallback
block.
Example:
[self.bridge callHandler:@"showAlert" data:@"Hi from ObjC to JS!"];
[self.bridge callHandler:@"getCurrentPageUrl" data:nil responseCallback:^(id responseData) {
NSLog(@"Current UIWebView page URL is: %@", responseData);
}];
Custom bundle
WebViewJavascriptBridge
requires WebViewJavascriptBridge.js.txt
file that is injected into web view to create a bridge on JS side. Standard implementation uses mainBundle
to search for this file. If you e.g. build a static library and you have that file placed somewhere else you can use this method to specify which bundle should be searched for WebViewJavascriptBridge.js.txt
file:
[WebViewJavascriptBridge bridgeForWebView:(UIWebView/WebView*)webView webViewDelegate:(UIWebViewDelegate*)webViewDelegate handler:(WVJBHandler)handler resourceBundle:(NSBundle*)bundle
Example:
[WebViewJavascriptBridge bridgeForWebView:_webView
webViewDelegate:self
handler:^(id data, WVJBResponseCallback responseCallback) {
NSLog(@"Received message from javascript: %@", data);
}
resourceBundle:[NSBundle bundleWithURL:[[NSBundle mainBundle] URLForResource:@"ResourcesBundle" withExtension:@"bundle"]]
];
Javascript API
document.addEventListener('WebViewJavascriptBridgeReady', function onBridgeReady(event) { ... }, false)
Always wait for the WebViewJavascriptBridgeReady
DOM event.
Example:
document.addEventListener('WebViewJavascriptBridgeReady', function(event) {
var bridge = event.bridge
// Start using the bridge
}, false)
bridge.init(function messageHandler(data, response) { ... })
Initialize the bridge. This should be called inside of the 'WebViewJavascriptBridgeReady'
event handler.
The messageHandler
function will receive all messages sent from ObjC via [bridge send:(id)data]
and [bridge send:(id)data responseCallback:(WVJBResponseCallback)responseCallback]
.
The response
object will be defined if if ObjC sent the message with a WVJBResponseCallback
block.
Example:
bridge.init(function(data, responseCallback) {
alert("Got data " + JSON.stringify(data))
if (responseCallback) {
responseCallback("Right back atcha!")
}
})
bridge.send("Hi there!")
bridge.send({ Foo:"Bar" })
bridge.send(data, function responseCallback(responseData) { ... })
Send a message to ObjC. Optionally expect a response by giving a responseCallback
function.
Example:
bridge.send("Hi there!")
bridge.send("Hi there!", function(responseData) {
alert("I got a response! "+JSON.stringify(responseData))
})
bridge.registerHandler("handlerName", function(responseData) { ... })
Register a handler called handlerName
. The ObjC can then call this handler with [bridge callHandler:"handlerName" data:@"Foo"]
and [bridge callHandler:"handlerName" data:@"Foo" responseCallback:^(id responseData) { ... }]
Example:
bridge.registerHandler("showAlert", function(data) { alert(data) })
bridge.registerHandler("getCurrentPageUrl", function(data, responseCallback) {
responseCallback(document.location.toString())
})
iOS4 support (with JSONKit)
Note: iOS4 support has not yet been tested in v2+.
WebViewJavascriptBridge uses NSJSONSerialization
by default. If you need iOS 4 support then you can use JSONKit, and add USE_JSONKIT
to the preprocessor macros for your project.
iOS中html5的交互:WebViewJavascriptBridge的更多相关文章
- iOS与HTML5交互方法总结(转)
今天小编在找技术文章的时候,发现这样一个标题:iOS与HTML5交互方法总结,怎么看着这么熟悉呢? 还以为是刚哥用了别的文章,点进去一看,原来是刚哥自己写的文章,他们转载的,而且还上了Dev St ...
- iOS与HTML5交互方法总结(修正)
摘要 看了不少别人写的博客或者论坛,关于iOS与HTML5交互方法大概主要有5种方式: 1. 利用WKWebView进行交互(系统API) 2. 利用UIWebView进行交互(系统API) 3. 苹 ...
- UIWebView中JS与OC交互 WebViewJavascriptBridge的使用
一.综述 现在很多的应用都会在多种平台上发布,所以很多程序猿们都开始使用Hybrid App的设计模式.就是在app上嵌入网页,只要写一份网页代码,就可以跑在不同的系统上.在iOS中,app多是通过W ...
- iOS中JS 与OC的交互(JavaScriptCore.framework)
iOS中实现js与oc的交互,目前网上也有不少流行的开源解决方案: 如:react native 当然一些轻量级的任务使用系统提供的UIWebView 以及JavaScriptCore.framewo ...
- iOS中使用UIWebView与JS进行交互
iOS中使用UIWebView与JS进行交互 前一段忙着面试和复习,这两天终于考完试了,下学期的实习也有了着落,把最近学的东西更新一下,首先是使用UIWebView与JS进行交互 在webView中我 ...
- iOS中UIWebView使用JS交互 - 机智的新手
iOS中偶尔也会用到webview来显示一些内容,比如新闻,或者一段介绍.但是用的不多,现在来教大家怎么使用js跟webview进行交互. 这里就拿点击图片获取图片路径为例: 1.测试页面html & ...
- iOS中js与objective-c的交互(转)
因为在iOS中没有WebKit.Framework这个库的,所以也就没有 windowScriptObject对象方法了.要是有这个的方法的话 就方便多了,(ps:MacOS中有貌似) 现在我们利用其 ...
- iOS中UIWebView使用JS交互
iOS中偶尔也会用到webview来显示一些内容,比如新闻,或者一段介绍.但是用的不多,现在来教大家怎么使用js跟webview进行交互. 这里就拿点击图片获取图片路径为例: 1.测试页面html & ...
- 在Html5中与服务器交互
转自原文 在Html5中与服务器交互 刚刚涉足职场,上头就要我研究HTML5,内嵌到手机上,这对我来说完全是一个陌生的领域,不过也正好给自己一个机会来学习,最近做到要跟服务器交互这部分,这部分可是卡了 ...
随机推荐
- 1.1 Introduction中 Topics and Logs官网剖析(博主推荐)
不多说,直接上干货! 一切来源于官网 http://kafka.apache.org/documentation/ Topics and Logs 话题和日志 (Topic和Log) Let's fi ...
- js数组遍历和对象遍历小结
数组的遍历 for循环 for(var j = 0,len = arr.length; j < len; j++){ console.log(arr[j]); } forEach,性能比for还 ...
- Django模板变量,过滤器和静态文件引用
模版路径查找 首先去settings.py里面找TEMPLATES ,在TEMPLATES下面找DIRS,找到就返回,没找到就继续往下,如果APP_DIRS设置为为Ture,那么就会到上面 INSTA ...
- GO语言学习(十九)Go 错误处理
Go 错误处理 Go 语言通过内置的错误接口提供了非常简单的错误处理机制. error类型是一个接口类型,这是它的定义: type error interface { Error() string } ...
- ORACLE 11G R2 DG_BROKER 之SWITCH OVER
官网:http://docs.oracle.com/cd/B12037_01/server.101/b10822/cli.htm 这个是有必要看一下. 注意本人已经完毕一次SWITCHOVER 所 ...
- CC2530定时器使用
定时器学习 文件夹 说明 依据数据手冊可知CC2530总共同拥有4个定时器,可是定时器2被系统占用,可用的仅仅有三个,分别为定时器1/3/4 Timer在协议栈的代码位置为hal_timer ...
- HTTP网络协议(三)
HTTP首部字段有四种类型:通用首部字段,请求首部字段,响应首部字段,实体首部字段. 通用首部字段: 首部字段 说明 Cache-Control 控制缓存的行为 Connection 逐跳首部.连接 ...
- tomcat的classloader机制
本系列博客打算分析一下tomcat7.x的源码,其中可能会穿插一些java基础知识的介绍 读tomcat的源码的时候,我建议和官方的User Guide一起阅读,明白tomcat做某件事情的目的之后 ...
- python课程:python3的数字与字符串
一下是基于python2的教程的 python中有 多个数据类型,和,两种字符串类型 他们都是不可变的.
- vue 图片lazyload
今天看到我一醉哥的一篇朋友圈分享:<不如我们从头来过 | 掘金> 看完之后,百感交集,互联网的浪潮使创业公司如雨后春笋般崛起, 每一个初创公司都会有一群怀着美好愿景的小伙伴, 但是当寒冬来 ...